List item with CheckBox not clickable

前端 未结 9 1928
误落风尘
误落风尘 2020-12-31 01:12

I have a list item which contains a CheckBox, and I want to be able to click on the CheckBox and on the list item itself. Unfortunately, there seems to be some sort of confl

9条回答
  •  清酒与你
    2020-12-31 01:43

    Late, but nevertheless a solution for all those who still need it.

    It is true that the built-in mechanism using:

    final ArrayAdapter adapter = new ArrayAdapter(
        getActivity(),
        android.R.layout.simple_list_item_multiple_choice, lst);
    

    does not allow both, ie click on the checkbox AND click on the list item. Wherever one clicks, the checkbox catches the event.

    However, if you create your own ArrayAdapter with getView like this, then it works fine:

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.list_item_ecu_fehler, null);
        }
    
        v.setFocusable(true);
        v.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            if (DEBUG)
                Log.i(this.getClass().getSimpleName(),
                    " ->>"
                        + Thread.currentThread().getStackTrace()[2]
                            .getMethodName());
            }
        });
    
                CheckBox selectedForClearingCB = (CheckBox) v
                .findViewById(R.id.checkBox);
    
    
            if (selectedForClearingCB != null) {
            selectedForClearingCB.setTag(position); //so we know position in the list       selectedForClearingCB.setChecked(true);
            selectedForClearingCB.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
    
                if (((CheckBox) v).isChecked()) {
                    if (DEBUG)
                    Log.i(this.getClass().getSimpleName(),
                        " -> CB checked: "
                            + Integer.toString((Integer) v
                                .getTag()));
    
                }
    
                }
            });
            }
        }
        return v;
        }
    
    }
    

提交回复
热议问题