'Make a whole view with sub-elements clickable
I have a vertical LinearLayout in my app where every row should get a more complex sub-view consisting of an image and two lines of text. Now I want to make the complete row clickable in order to start an other action. This means the whole thing should react on a click: the base view which holds the other elements, the image and even the two lines of text.
My question: what is the best approach for this? I can't use a simple button for the complete row and as far as I know I can't set an onClick-Handler for view/image/labels?
Any idea how this could be done?
Thanks!
Solution 1:[1]
The easiest option would be to put android:descendantFocusability="blocksDescendants" on your parent view, this will block any child view from taking clicks from the parent, then put a click listener on the parent only.
This is assuming you don't care on which child view exactly the user clicked within the parent.
<LinearLayout
android:id="@+id/parent"
...
android:clickable="true"
android:descendantFocusability="blocksDescendants" >
<TextView
... />
<ImageButton
... />
</LinearLayout>
and in code:
LinearLayout parent = (LinearLayout) findViewById(R.id.parent);
parent.setOnClickListener(...);
Solution 2:[2]
This is how I did it. Just loop over the childen and make then non clickable. This works even if you are using clickable items inside root view.
rootView.apply {
descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS
isClickable = true
setOnClickListener {
Snackbar.make(it, "$data", Snackbar.LENGTH_LONG).show()
}
children.forEach {
it.isClickable = false
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | marmor |
| Solution 2 |
