Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to propagate click event to LinearLayout childs and change their drawable

I would like to create a linear layout which would behave similarly to ImageButton.

<LinearLayout
    android:id="@+id/container"
    style="?WidgetHomeIconContainer">            

    <ImageView
        android:id="@+id/icon"
        style="?WidgetHomeIcon" />

    <TextView
        android:id="@+id/title"
        style="?WidgetHomeLabel"             
        android:text="@string/title"
        android:textAppearance="?attr/TextHomeLabel" />
</LinearLayout>

In styles of ImageView, TextView and LinearLayout, I set a selectors for all states.

Now:

  • when I click on ImageView (I tried it also with ImageButton) - it behaves correctly and the image is changed according the selector xml.
  • when I click on LinearLayout - the linear layout is clicked, but the the ImageView and TextView don't change it's drawable/appearance

So I would like to do the following. When I click on parent LinearLayout, I need to change all it's childs to pressed state.

I tried to add following code to LinearLayout onClickListener to propagate the click:

@Override
public void onClick(View v)
{
    LinearLayout l = (LinearLayout) v;
    for(int i = 0; i < l.getChildCount(); i++)
    {
        l.getChildAt(i).setClickable(true);
        l.getChildAt(i).performClick();
    }
}

But it still reamins the same. Thank you very much for any help.

like image 975
Bhiefer Avatar asked Apr 16 '12 08:04

Bhiefer


3 Answers

Put

android:duplicateParentState="true"

in your ImageView and TextView..then the views get its drawable state (focused, pressed, etc.) from its direct parent rather than from itself.

like image 94
5hssba Avatar answered Nov 13 '22 04:11

5hssba


Not only make for every child:

android:duplicateParentState="true"

But also additionally:

android:clickable="false"  

This will prevent unexpected behaviour (or solution simply not working) if clickable child views are used.

SO Source

like image 30
Morphing Coffee Avatar answered Nov 13 '22 06:11

Morphing Coffee


After having the same problem some months later, I found this solution:

private void setOnClickListeners() {
    super.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            onClick(v);
        }
    });
    for (int index = 0; index < super.getChildCount(); index++) {
        View view = super.getChildAt(index);
        view.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                onClick(v);
            }
        });
    }
}

protected void onClick(View v) {
    // something to do here...
}
like image 1
Bernd Avatar answered Nov 13 '22 05:11

Bernd