Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Kotlin child onClick blocks parent OnTouch

I have this layout hierarchy:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.xxxxxx.Widget
        android:id="@+id/widget1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <com.xxxxxx.Widget
        android:id="@+id/widget2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    </LinearLayout>
</LinearLayout>

I have touch Events for the Parent LinearLayout like this:

parent.setOnTouchListener(myCustomTouchParent)

    class MyCustomTouchParent(ctx: Context): View.OnTouchListener {

        private var isScrollingDown = false
        private var isScrollingUp = false
        private val myGestureDetected = GestureDetector(ctx, MyGestureListener())

        var onRecyclerViewMovingDown: (() -> Unit)? = null

        override fun onTouch(p0: View?, e: MotionEvent): Boolean {
            myGestureDetected.onTouchEvent(e)

            when(e.action){
                MotionEvent.ACTION_UP -> {
                    if (isScrollingDown) {
                        onRecyclerViewMovingDown?.invoke()
                    }
                }

                MotionEvent.ACTION_DOWN -> {
                    Log.i("TAg", "Action Down")
                    isScrollingDown = false
                    isScrollingUp = false

                }
            }
            return true
        }

        inner class MyGestureListener: GestureDetector.SimpleOnGestureListener() {
            override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean {
                if(e2.y - e1.y > 0){
                    isScrollingUp = true
                } else if(e2.y - e1.y < 0){
                    isScrollingDown = true
                }
                return super.onScroll(e1, e2, distanceX, distanceY)
            }


        }
    }

Basically, this will detect a 'Scroll Up' event on the parent, and will perform some animations. The problem is, as soon as I set a click listener for widget1 and widget2, the touch event of the parent is no longer working. Is there any workaround for this?

like image 223
johnny_crq Avatar asked Dec 18 '25 11:12

johnny_crq


1 Answers

You have to override both onTouchListeners on your children views and return false, that will make them not override their parent ontouch.

widget1.onTouch { view, motionEvent -> return@onTouch false }
widget2.onTouch { view, motionEvent -> return@onTouch false }
like image 119
Eefret Avatar answered Dec 19 '25 23:12

Eefret