0

我一直在寻找与 ListView 中的父布局(项目)共享子元素状态的解决方案。

明确地说,我需要的是:当我按下单元格时,所有子项都处于“pressed_state”,但我还想要的是当我按下单元格中的特定按钮时,整个单元格也会被按下。但是,我需要android:duplicateParentState="true"后者才能工作,因此android:addStatesFromChildren="true"无法定义。

我是否需要为该特定按钮使用 onTouchEvent 并以编程方式将按下状态设置为单元格并在按下时释放它?

4

1 回答 1

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);
            }
        }
    }
}

有了这个,它就会工作。

于 2013-09-12T12:54:36.403 回答