简体   繁体   中英

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!

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(...);

You just need to add clickable tag true in xml to your main view eg relativelayout or linearlayout. That will work

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
    }
}

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