如果你把 Scrollview 放在自定义的 GridView 中,当你触摸这个自定义的 GridView 时,ScrollView 会获得焦点,所以你的OnTouchEvent 无法执行。
我们可以为自定义 GridView 设置一个填充,如下面的代码所示。为了演示上述结论,我将自定义 GridView 的背景颜色设置为绿色,并将 ScrollView 的背景颜色设置为红色
<minitormediamanager:CustomGridView Margin="20,35,20,20" Padding="20" BackgroundColor="Green">
<ScrollView HeightRequest="50" BackgroundColor="Red">
<StackLayout>
<Label Text="By default, a Grid contains one row and one column." />
<Label Text="By default, a Grid contains one row and one column." />
<Label Text="By default, a Grid contains one row and one column." />
<Label Text="By default, a Grid contains one row and one column." />
<Label Text="By default, a Grid contains one row and one column." />
<Label Text="By default, a Grid contains one row and one column." />
<Label Text="By default, a Grid contains one row and one column." />
<Label Text="By default, a Grid contains one row and one column." />
<Label Text="By default, a Grid contains one row and one column." />
</StackLayout>
</ScrollView>
</minitormediamanager:CustomGridView>
这是我的GridcustomRenderer 代码。
[assembly: ExportRenderer(typeof(MinitorMediaManager.CustomGridView), typeof(CustomGridViewRenderer))]
namespace MinitorMediaManager.Droid
{
// <Xamarin.Forms.Grid, Android.Views.View>
public class CustomGridViewRenderer : ViewRenderer<MinitorMediaManager.CustomGridView, Android.Views.View>
{
public CustomGridViewRenderer(Context context) : base(context)
{
}
public override bool OnTouchEvent(MotionEvent e)
{
Console.WriteLine("xxxxxxxxxxxxxxxxxxxxxxxxxx");
return base.OnTouchEvent(e);
}
}
}
您可以看到以下正在运行的 GIF。如果我滚动或点击 ScrollView(红色背景),OnTouchEvent 将不会被执行,但如果我点击 GridView 的 padding(绿色背景),OnTouchEvent 将被执行。
最后,如果你想实现一个触摸事件,可以在子控件中完成,不要添加GirdView或StackLayout(如果你没有padding)..