我一直在寻找与ListView中的父布局(item)共享子元素状态的解决方案。
显然,我需要的是:当我按下单元格时,所有子项都在“pressed_state”中,但我也想要的是当我按下单元格中的特定按钮时,整个单元格也会被按下。但是,我需要android:duplicateParentState="true"
才能使后者工作,因此android:addStatesFromChildren="true"
无法定义。
我是否需要对该特定按钮使用onTouchEvent并以编程方式将按下的状态设置为单元格并在新闻稿中将其释放?
答案 0 :(得分:0)
我最终使用onTouchListener作为特定按钮,而不是同时使用xml中的android:duplicateParentState
和android:addStatesFromChildren
。
以下是我在CustomExpandableListAdapter中所做的事情:
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
/* code before */
ImageButton button = (ImageButton) convertViewNotNull.findViewById(R.id.ofButton);
button.setOnClickListener(onClickListenerInCodeBefore);
View.OnTouchListener onTouchCell = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
setPressedState(v, true);
break;
case MotionEvent.ACTION_UP:
setPressedState(v, false);
v.performClick();
break;
default:
break;
}
return true;
}
};
button.setOnTouchListener(onTouchCell);
}
// code can be optimized
private void setPressedState(View v, boolean pressed) {
ViewGroup parent = (ViewGroup) v.getParent();
final int count = parent.getChildCount();
for (int i = 0; i < count; i++) {
View view = parent.getChildAt(i);
view.setPressed(pressed);
if (view instanceof RelativeLayout ||
view instanceof LinearLayout) {
ViewGroup group = (ViewGroup) view;
final int size = group.getChildCount();
for (int j = 0; j < size; j++) {
View child = group.getChildAt(j);
child.setPressed(pressed);
}
}
}
}
有了这个,它就会起作用。