如何在滚动后还原 ViewGroup 对触摸事件的处理



我有一个包含按钮(子)的 ScrollView(父级)。问题在于,在滚动时,父级获得了TouchEvents的所有权,并且再也不会将其发送给其子级。因此,按钮永远不会收到 UP 事件,并且永远保持按下状态。

我需要孩子在滚动后接收 UP 事件,因此

  • 让父级在滚动后再次调度触摸事件(例如,在 UP 上)
  • 让父级只侦听 Move 事件,并调度其余事件(向下、向上等)

我正在使用Xamarin,顺便说一句。谢谢。

这种简单的 XAML 设置会产生以下问题:

<ScrollView
    Orientation="Horizontal">
    <Button Text="drag me horizontally" 
        HorizontalOptions="Center"
        VerticalOptions="CenterAndExpand"
        TextColor="White"
        WidthRequest="500">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup Name="DefaultStates">
                <VisualState x:Name="Normal">
                    <VisualState.Setters>
                        <Setter Property="BackgroundColor" Value="Black" />
                    </VisualState.Setters>
                </VisualState>
                <VisualState x:Name="Pressed">
                    <VisualState.Setters>
                        <Setter Property="BackgroundColor" Value="Red" />
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Button>
</ScrollView>

我通过修改您的代码解决了这个问题,如下所示:

MainPage.xamal:

<ScrollView x:Name ="Scroll1"
    Orientation="Horizontal" >
    <Button x:Name="TestButton1" Text="drag me horizontally" 
        HorizontalOptions="Center"
        VerticalOptions="CenterAndExpand"
        TextColor="White"
        WidthRequest="500">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup Name="DefaultStates">
                <VisualState x:Name="Normal">
                    <VisualState.Setters>
                        <Setter Property="BackgroundColor" Value="Black" />
                    </VisualState.Setters>
                </VisualState>
                <VisualState x:Name="Pressed">
                    <VisualState.Setters>
                        <Setter Property="BackgroundColor" Value="Red" />
                    </VisualState.Setters>
                </VisualState>
                <VisualState x:Name="Released">
                    <VisualState.Setters>
                        <Setter Property="BackgroundColor" Value="Black" />
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Button>
</ScrollView>

MainPage.xaml.cs:

public MainPage()
{
    InitializeComponent();
    TestButton1.Pressed += (sender, args) =>
    {
        VisualStateManager.GoToState(TestButton1, "Pressed");
    };
    TestButton1.Released += (sender, args) =>
    {
        VisualStateManager.GoToState(TestButton1, "Released");
    };
    Scroll1.Scrolled += (sender, args) =>
    {
        VisualStateManager.GoToState(TestButton1, "Released");
    };
}

最新更新