Change CheckBox state on List item click?

前端 未结 4 1978
南方客
南方客 2020-12-15 17:52

I have a list and a checkbox in every row of it. I want that whenever I click on a row, the checkbox changes its state accordingly.

checkbox.xml

<         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 18:14

    You need to use findViewById to get a pointer to your checkbox:

    protected void onListItemClick(ListView l, View v, int position, long id) {
    
        Toast.makeText(getApplicationContext(), "You have selected item no."
                     +(position+1)+"", Toast.LENGTH_SHORT).show();
    
        super.onListItemClick(l, v, position, id);
    
        if (v != null) {
            CheckBox checkBox = (CheckBox)v.findViewById(R.id.Checkbox);
            checkBox.setChecked(!checkBox.isChecked());
        }
    }
    

    If you are recieving the onClick event then v should never be null but I have put on the appropriate checks.

提交回复
热议问题