6

我想知道是否有任何方法可以通过代码选择/选中多选列表首选项的所有框。

这是我的首选 XML 文件。

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

这些是数组:

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

现在,我列表中的第一项将是“所有团队”,我希望这样当用户选择所有团队时,所有团队名称旁边都应该有一个检查。

应选中所有框

4

1 回答 1

0

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
        }
    }
});
于 2014-09-29T08:20:51.547 回答