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.

<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.

All boxes should be checked


回答1:


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
        }
    }
});


来源:https://stackoverflow.com/questions/23274340/how-can-i-implement-a-select-all-option-for-multi-select-list-preference

工具导航Map