I have a LinearLayout with a selectable text view
<LinearLayout
android:id="@+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/rectangular_background">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textIsSelectable="true"
android:text="Clickable"/>
</LinearLayout>
Assigned a click listener on LinearLayout
linear_layout.setOnClickListener {
Toast.makeText(context, "Linear Layout clicked", Toast.LENGTH_SHORT).show()
}
Toast is not shown on click of text view when it has selectable text. I have tried a solution in this answer by adding following code in generic function to be used for all text views.
val textGestureDetector = GestureDetectorCompat(context, GestureDetector.SimpleOnGestureListener())
textGestureDetector.setOnDoubleTapListener(object : GestureDetector.OnDoubleTapListener {
override fun onDoubleTap(e: MotionEvent?): Boolean = false
override fun onDoubleTapEvent(e: MotionEvent?): Boolean = false
override fun onSingleTapConfirmed(e: MotionEvent?): Boolean {
textView.performClick()
return true
}
})
textView.setOnTouchListener { _, event ->
textGestureDetector.onTouchEvent(event)
false
}
This solution does work when we assign click listener on text view but when text view has no click listener, the click event is not propagated to linear layout.
Since there can be multiple child text views in the linear layout, I do not want to explicitly write code to invoke parent's click listener on each child's click. Is there a way to fix this issue with a generic solution?
Edit: Ideally I would want to create a custom text view that correctly propagates the click irrespective of text being selectable or not. That will help in solving this issue throughout my app. Correctly propagating click would mean 3 things:
- Double clicking on textview selects the text.
- When text view has click listener, single click invokes it
- When text view has no click listener, single click invokes the click listener of the ancestor that has one. Note that this scenario already works well if text is not selectable
What I understood you want to pass a click of selectable text view to its parent.
To do this perform clicking on parent in
onSingleTapConfirmedof the child view (selectable textView).