Search code examples
androidcheckboxlistischecked

Android Development - isChecked Checkbox using simple_list_item_multiple_choice and CHOICE_MODE_MULTIPLE


I am using simple_list_item_multiple_choice with list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); to create a list of check boxes populated from a database query. I am then using onListItemClick to handle the clicking of the list, again that is working fine. What I can find no way of doing (after 5 days) is writing an if statement based on whether or not the check box attached to the list item is checked. What I need is the equivalent of the example below which works perfectly for a check box where I can use the android:onClick element to fire the method below.

public void onCheckboxClicked(View v) {
        // Perform action on clicks, depending on whether it's now checked
        if (((CheckBox) v).isChecked()) {
            Toast.makeText(this, "Selected", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Not selected", Toast.LENGTH_SHORT).show();
        }
    }

This is critical to my app so any advice would be greatly appreciated. Below is the simpleCusrorAdapter is am using:

 Cursor cursor3 = db.rawQuery("SELECT _id, symname FROM tblsymptoms WHERE _id IN ("+sympresult+") ", null);

        adapter = new SimpleCursorAdapter(
                this, 
                android.R.layout.simple_list_item_multiple_choice,
                cursor3, 
                new String[] {"symname","_id"}, 
                new int[] {android.R.id.text1});
        setListAdapter(adapter);
        ListView list=getListView();
        list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

Solution

  • I have solved the problem after finding this very useful blog item

    I changed my onListItemClick to the following and it works like a dream:

    public void onListItemClick(ListView parent, View view, int position, long id) {
    
    
          CheckedTextView check = (CheckedTextView)view;
          check.setChecked(!check.isChecked());
          boolean click = !check.isChecked();
          check.setChecked(click);
          if (click) {
                Toast.makeText(this, "Not Selected", Toast.LENGTH_SHORT).show();
          } else {
              Toast.makeText(this, "Selected", Toast.LENGTH_SHORT).show();
          } 
    }