James Fazio
James Fazio

Reputation: 6450

Android Get Checkbox Info from ListView

I have a ListView with multiple checkboxes (one for each list item). What would be the best way to create an array containing information from the selected checkboxes.

For Example, here's a list.

  Item 1 "Ham" Checked
  Item 2 "Turkey" NotChecked
  Item 3 "Bread" Checked  

I would like to create an array containing "ham" and "turkey"

Upvotes: 0

Views: 4156

Answers (1)

Sam
Sam

Reputation: 86948

If you used ListView's built-in checkbox method with setChoiceMode() then you only need to call getCheckedItemIds() or getCheckedItemPositions().

public class Example extends Activity implements OnClickListener {
    ListView mListView;
    String[] array = new String[] {"Ham", "Turkey", "Bread"};

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, array);

        mListView = (ListView) findViewById(R.id.list);
        mListView.setAdapter(adapter);
        mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    public void onClick(View view) {
        SparseBooleanArray positions = mListView.getCheckedItemPositions();
        int size = positions.size();
        for(int index = 0; index < size; index++) {
            Log.v("Example", "Checked: " + array[positions.keyAt(index)]);
        }
    }
}

If the Adapter is bound to a Cursor, then this becomes much more practical.

Upvotes: 2

Related Questions