7

我正在开发一个示例应用程序来学习 android。它应该显示一个多选列表,当用户单击按钮时,它应该显示在顶部的 TextView 中选择的项目。似乎当我尝试从 ListView 检索所选项目时,总是返回一个空数组。谁能向我解释为什么会这样以及我缺少什么才能使其正常工作?(仅供参考,代码是格兰特艾伦从 Android 4 开始的修改程序)

这是布局xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView
        android:id="@+id/selection"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/getSelections"
        android:text="Show Selections"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="listSelected" />
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
        android:drawSelectorOnTop="false"
        android:choiceMode="multipleChoice" />
</LinearLayout>

这是相关的Java:

package com.commonsware.android.checklist;

import android.os.Bundle;
import android.app.ListActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.view.*;

public class ChecklistDemo extends ListActivity {
    private static final String[] items={"lorem", "ipsum", "dolor",
                    "sit", "amet",
                    "consectetuer", "adipiscing", "elit", "morbi", "vel",
                    "ligula", "vitae", "arcu", "aliquet", "mollis",
                    "etiam", "vel", "erat", "placerat", "ante",
                    "porttitor", "sodales", "pellentesque", "augue", "purus"};

    private TextView selection;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        setListAdapter(new ArrayAdapter<String>(this,
                                                android.R.layout.simple_list_item_multiple_choice,
                                                items));
        selection = (TextView)findViewById(R.id.selection);

    }

    public void listSelected(View view) {
        long[] chosenOnes = getListView().getCheckedItemIds();
        selection.setText("Items selected: ");
        selection.setText(Integer.toString(chosenOnes.length));
        for (long x:chosenOnes) {
            int i = Long.valueOf(x).intValue();
            selection.setText(selection.getText() + ", " + items[i]);           
        }

    }

}
4

1 回答 1

14

请参阅文档,仅当您的适配器具有稳定的 id 时,该方法getCheckedItemIds()才会返回有效结果。相反,您可以使用

SparseBooleanArray array = this.getListView().getCheckedItemPositions();

希望这会帮助你=)

于 2012-07-11T20:40:32.103 回答