3

我不知道如何确切地解释这个问题,但我会尝试。我有一个包含多个项目的 ListView。每个项目里面都有一个TextView和两个ImageView。我希望在单击它们时更改 ImageView,并且当我长时间按下 ListView 项时,我想打开一个上下文菜单。

对于 ImageView,一切正常。对于整个项目,我可以在长按后显示上下文菜单,但我的问题是,例如,当我按下 TextView 时,ImageView 也会发生变化。

我的代码的一些片段:

列表视图项:

     <TextView 
      android:id="@+id/title"
      android:textColor="@color/black"
      android:maxLines="2"
      android:textSize="14dip" 
            />
    <ImageView
        android:id="@+id/minus"
        android:src="@drawable/minusbutton"
        android:adjustViewBounds="true"
        android:gravity="center"
    />
    <ImageView 
        android:id="@+id/plus"
        android:src="@drawable/plusbutton"
        android:adjustViewBounds="true"
        android:gravity="center"
    />

Drawable 改变加号按钮的状态:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false"
      android:drawable="@drawable/button_add_normal_disabled" />
<item android:state_enabled="true"
      android:state_pressed="true"
      android:drawable="@drawable/button_add_pressed" />
<item android:state_enabled="true"
      android:state_focused="true" 
      android:state_pressed="false" 
      android:drawable="@drawable/button_add_active" />
<item android:state_enabled="true"
      android:state_focused="false" 
      android:state_pressed="false"
      android:drawable="@drawable/button_add_normal" />

我希望你能理解我的问题。我认为视图的所有子视图都会受到父事件的影响,但我不确定。

你有解决方案吗?提前致谢

4

3 回答 3

6

解决这个问题最简单的方法是继承 viewgroup 并覆盖 dispatchSetPressed。

这是一个例子

public class DuplicateParentStateAwareLinearLayout extends LinearLayout {

    public DuplicateParentStateAwareLinearLayout(Context context) {
        super(context);
    }

    public DuplicateParentStateAwareLinearLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public DuplicateParentStateAwareLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /*
     * By default ViewGroup call setPressed on each child view, this take into account duplicateparentstate parameter
     */
     @Override
     protected void  dispatchSetPressed(boolean pressed) {
          for (int i = 0; i < getChildCount(); i++) {
             View child = getChildAt(i);
             if (child.isDuplicateParentStateEnabled()){
                 getChildAt(i).setPressed(pressed);
             }
         }
      }
}

使用此方法的问题是,您必须为您想要的每个项目和不应该具有此行为的子项目设置 duplicateparentstate 为 true。

于 2012-09-04T17:54:52.693 回答
3

我相信发生的事情是 ListView 正在设置项目的 ViewGroup 的状态,而孩子们正在复制父母的状态。所以它实际上是 state_pressed 中的行,它被继承到行内的其他视图。有一个属性,android:duplicateParentState="false",我认为应该解决这个问题。

于 2010-06-16T19:28:58.143 回答
0

简单且可能不是很优雅的解决方案 - 为您的图像视图摆脱 statefull drawable 并在 OnItemClickListener() 中处理此项目的呈现。我可能会更改适配器中 Item 的状态,然后适配器中的 getView 应该根据您的状态放置正确的图像。

于 2010-04-09T14:00:33.487 回答