Search code examples
androidchildviews

Complext "button" (LinearLayout with child views) with background drawable - on children click doesn't reflect the "state_pressed"


I have a LinearLayout that has 2 children: a ImageView aligned left and a TextView aligned right.

I've set the background of the LinearLayout to be a @drawable XML resource that has two <item> tags. One of them has android:state_pressed="true". Also, the LinearLayout has android:clickable="true".

When the LinearLayout is clicked it correctly changes its background to the android:state_pressed style, but clicking on one of its children doesn't propagate the click action up to the LinearLayout.

Is there a way to easily achieve a click state on the parent view when a child view is clicked?


Solution

  • not sure if it works for your specific implementation, but a very easy way of achieving this "complex" button is by making a normal button and using android:drawableLeft or android:drawableRight or android:drawableTop or android:drawableBottom and android:drawablePaddig to achieve the same visual result in just one view.

    for example:

    <LinearLayout orientation=vertical>
        <ImageView/>
        <TextView/>
    </LinearLayout>
    

    is pretty much the same as

    <Button
       drawableLeft="@drawable/..."
       text="..."
    />
    

    that way your whole layout is simpler and the pressed states works out-of-the-box.