How can I implement a 'Select all' option for Multi Select List Preference?

时光毁灭记忆、已成空白 提交于 2019-12-05 00:13:09


I want to know if there is any way to be able to select/check all boxes of the Multi-select List Preference through code.

This is my XML file for the preference.

    android:summary="This is a list to choose from"
    android:title="Teams to Follow" />


And these are the arrays:

<string-array name="list">
    <item>All Teams</item>
<string-array name="lValues">

Now, the first item of my list will be 'All Teams' I want to make it such that the moment a user selects All Teams, all the team names should have a check next to them.


Here's what I used, (nb. you will need to change adapter.getCount() to array.length where you have created your array from resource):

// create the dialog
final AlertDialog dialog = new AlertDialog.Builder(getActivity());
// set handlers for button presses etc.

// ....

// Set the click listener specifically for the 0th element
final ListView lv = dialog.getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long viewid) {
        System.out.println("clicked" + position);
        CheckedTextView textView = (CheckedTextView) view;
        if(position == 0) {
             if(textView.isChecked()) {
                 SparseBooleanArray checkedPositions = lv.getCheckedItemPositions();
                 for (int i = 1; i < adapter.getCount(); i++) {
                    if(!checkedPositions.get(i)) {
                        lv.setItemChecked(i, true);
             } else {
                 for(int i = 1; i < adapter.getCount(); i++) {
                     lv.setItemChecked(i, false);
        } else {
           // handle clicks for non-top element