Android:即使指定duplicateParentState,子元素也与父级共享压缩状态

Rau*_*ait 22 android android-layout

我有一个SlidingDrawer元素,其中包含一个RelativeLayout元素,其中包含一些Button子元素:

<SlidingDrawer>
  <RelativeLayout>
    <LinearLayout>
      <Button android:background="@drawable/foo.xml" android:duplicateParentState="false">
      <Button android:background="@drawable/bar.xml" android:duplicateParentState="false">
    </LinearLayout>
  </RelativeLayout>
</SlidingDrawer>
Run Code Online (Sandbox Code Playgroud)

foo.xml和bar.xml具有根据状态应用不同图像的选择器:

<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>
Run Code Online (Sandbox Code Playgroud)

我看到的问题是,当我点击滑动抽屉手柄时,按下按钮会触发按下状态,即使我指定duplicateParentState为假,它们也会被按下.

Rau*_*ait 26

LinearLayout用子类覆盖类.在该子类中重写该setPressed方法,并且不执行任何操作:

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.
    }
}
Run Code Online (Sandbox Code Playgroud)

替换LinearLayoutUnpressableLinearLayout.的实例.


Rom*_*Guy 10

无需将duplicateParentState设置为false.如果您以某种方式使父点击可能会发生这种情况.默认情况下,按下的状态将传播给子项.确保您的LinearLayout和RelativeLayout不可点击.

  • 这也发生在ICS上吗?我对它有不同的行为.单击未传播. (6认同)