简体   繁体   中英

Android swipe gesture not working for child views

I have a layout with some clickable views in it. I have implemented swipe gesture as per this . This is working great if you swipe in an empty area, but it does not work if you start swiping inside one of the views inside the layout.

How can this be avoided? Adding onSwipeListener to ever single view in the activity seems insane. Is there a better way?

my working solution to this problem is using an invisible layer above the view with children as following:

  <RelativeLayout
        android:id="@+id/contentLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/linearLayout"
        android:layout_alignStart="@+id/linearLayout"
        android:layout_alignParentTop="true"> 
        ... 
  </RelativeLayout>

  <View
        android:id="@+id/gesture_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/linearLayout"
        android:layout_alignStart="@+id/linearLayout"
        android:layout_alignParentTop="true"
        android:focusable="true"
        android:focusableInTouchMode="true" />

where contentLayout contains multiple children including some buttons.

Second step is catching touch events on this gesture_view and proxying them to both contentLayout and my GestureDetector code (similar to the one you linked on the question) as following:

gesture_view.setOnTouchListener { _, event ->
    contentLayout.dispatchTouchEvent(event)
    gestureListener.onTouch(event)
    true
}

Note, you need to be careful about how you deliver the events to the view behind gesture_view . Simply contentLayout#onTouch will not work. It has to be contentLayout.dispatchTouchEvent

Set android:clickable=false in your child views. This will prevent them from intercepting the touch events from the parent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM