Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How catch click event by root view for all children?

please see below code and say me its solution.

I have tree view same below

<RelativeLayout id="parent">

    <RelativeLayout id="container1">
       <view .../>
    </RelativeLayout>

   <RelativeLayout id="container2">
       <view .../>
    </RelativeLayout>

</RelativeLayout>

in activity:

ViewGroup parent = findViewById(R.id.parent);

parent.setOnClickListener(new ...);

I want when click on any children of parent view and children of children, parent's click event be fire.

parent view is a ViewHolder for ListView.

I test many code but not work

like, add to parent root

android:clickable="true"
android:focusable="true"

and false above for children, but :(

like image 578
Ali Bagheri Avatar asked Sep 14 '25 20:09

Ali Bagheri


1 Answers

You will need to set the click listener on each child that is added to the parent. Something like:

private void setChildListener(View parent, View.OnClickListener listener) {
    parent.setOnClickListener(listener);
    if (!(parent instanceof ViewGroup)) {
        return;
    }

    ViewGroup parentGroup = (ViewGroup) parent;
    for (int i = 0; i < parentGroup.getChildCount(); i++) {
        setChildListener(parentGroup.getChildAt(i), listener);
    }
}

This will recursively set set each view (including the initial one to the same listener.

You could also try and capture the onTouch event stealing the clicks from the subviews.

This question is a little strange to me. What behavior are you going for? When the user clicks do you want several things to happen depending on how many subviews the parent has?

like image 174
J Blaz Avatar answered Sep 16 '25 09:09

J Blaz