简体   繁体   中英

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

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.

<MultiSelectListPreference
    android:entries="@array/list"
    android:entryValues="@array/lValues"
    android:key="list"
    android:summary="This is a list to choose from"
    android:title="Teams to Follow" />

</PreferenceScreen>

And these are the arrays:

<string-array name="list">
    <item>All Teams</item>
    <item>Team1</item>
    <item>Team2</item>
    <item>Team3</item>
    <item>Team4</item>
</string-array>
<string-array name="lValues">
    <item>All</item>
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <item>4</item>
</string-array>

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.setItemsCanFocus(true);
lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(new OnItemClickListener() {
    @Override
    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
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM