Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Child elements sharing pressed state with their parent even when duplicateParentState specified

I have a SlidingDrawer element which contains a RelativeLayout element which contains some Button child elements:

<SlidingDrawer>
  <RelativeLayout>
    <LinearLayout>
      <Button android:background="@drawable/foo.xml" android:duplicateParentState="false">
      <Button android:background="@drawable/bar.xml" android:duplicateParentState="false">
    </LinearLayout>
  </RelativeLayout>
</SlidingDrawer>

foo.xml and bar.xml have selectors which apply different images depending on the state:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_focused="true" android:drawable="@drawable/foo_selected" />
  <item android:state_pressed="true" android:drawable="@drawable/foo_selected" />
  <item android:state_enabled="false" android:drawable="@drawable/foo_disabled" />
  <item android:drawable="@drawable/foo_normal" /> 
</selector>

The problem I am seeing is that when I click on the sliding drawer handle, the pressed state gets triggered for the buttons and they look pressed too, even though I've specified duplicateParentState to false.

like image 352
Raul Agrait Avatar asked Jul 19 '11 03:07

Raul Agrait


2 Answers

Override the LinearLayout class with a subclass. In that subclass override the setPressed method and do nothing like so:

public class UnpressableLinearLayout extends LinearLayout
{
    @Override
    public void setPressed(boolean pressed)
    {
        // Do nothing here. Specifically, do not propagate this message along
        // to our children so they do not incorrectly display a pressed state
        // just because one of their ancestors got pressed.
    }
}

Replace LinearLayout with an instance of UnpressableLinearLayout.

like image 93
Raul Agrait Avatar answered Nov 10 '22 13:11

Raul Agrait


There is no need to set duplicateParentState to false. This would happen if you make the parent clickable somehow. By default, the pressed state is propagated to the children. Make sure your LinearLayout and RelativeLayout are not clickable.

like image 12
Romain Guy Avatar answered Nov 10 '22 13:11

Romain Guy