Change CheckBox state on List item click?

前端 未结 4 1975
南方客
南方客 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:01
    CheckBox checkBox = (CheckBox) v.findViewById(R.id.CheckBox);
    checkBox.setChecked(true);
    
    0 讨论(0)
  • 2020-12-15 18:07

    Here is the full code, you can add this after setting the addapter:

    list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
    
    
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
               String message = "Item " + position;
               Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
    
                CheckBox cb = (CheckBox) view.findViewById(R.id.checkbox);
                cb.setChecked(!cb.isChecked());
    
    
            }
    
    
        });
    
    0 讨论(0)
  • 2020-12-15 18:09

    Inside the onListItemClick do this:

    CheckBox cb = (CheckBox) v.findViewById(R.id.CheckBox);
    cb.setChecked(!cb.isChecked());
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题