我不知道如何解释这个问题,但我会尝试。我有一个包含多个项目的 ListView。每个item里面都有一个TextView和两个ImageView。当我点击它们时,我希望 ImageView 发生变化,当我长时间按下 ListView 项目时,我想打开一个上下文菜单。
对于 ImageView,一切正常。对于整个项目,我可以在长按后显示上下文菜单,但我的问题是,例如,当我按下 TextView 时,ImageView 也会发生变化。
Somo 代码 fragment :
ListView 项目:
<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"
/>
可绘制以更改加号按钮的状态:
<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" />
希望您能理解我的问题。我认为一个 View 的所有 subview 都受到父 View 中事件的影响,但我不确定。
你有解决办法吗?提前致谢
最佳答案
解决这个问题最简单的方法就是继承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。
关于android - 单击 ListView 项目会更改项目内元素的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2607698/