Android:即使指定了duplicateParentState,子元素与其父元素共享按下状态

23

我有一个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>

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>

我遇到的问题是,当我点击滑动抽屉句柄时,按钮的按下状态也被触发了,并且它们看起来也被按下了,尽管我已经将 duplicateParentState 指定为 false。


1
通过子类化ViewGroup并重写dispatchSetPressed方法,可以更好地解决这个问题。我已经在这个线程https://dev59.com/L03Sa4cB1Zd3GeqPsBSF#12268890上发布了解决方案。 - Gomino
我认为我的问题可以回答你的问题。http://stackoverflow.com/questions/14179431/android-child-view-sharing-pressed-state-from-its-parent-view-in-jelly-bean - jinglezju
3个回答

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.
    }
}

UnpressableLinearLayout 的实例替换 LinearLayout


1
为了避免为其他视图(RelativeLayout,FrameLayout等)编写新的自定义布局,请查看我的解决方案,它更简单。 - user1521536

12

无需将duplicateParentState设置为false。如果你使父元素可点击,它会自动发生。默认情况下,按下的状态会传递给子元素。确保LinearLayout和RelativeLayout不可点击。


嗨,Romain Guy,你能在某个地方记录一下这个吗?昨天我遇到了这个问题,通过查看ViewGroup的源代码解决了它。似乎有些状态会传递给子元素,而有些则不会。 - Randy Sugianto 'Yuku'
6
这个问题在ICS上也会发生吗?我在ICS上遇到了不同的行为,点击事件没有被传递。 - neteinstein

0

SeekBar有相同的情况。

SeekBar的设置:

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

对我有效


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接