使用getListView()时清空数组.getCheckedItemIds()

时间:2012-07-11 20:13:26

标签: android

我正在开发一个示例应用程序来学习android。它应该显示一个多选列表,当用户点击该按钮时,它应该显示在顶部的TextView中选择的项目。当我尝试从ListView中检索所选项时,似乎总是返回一个空数组。任何人都可以向我解释为什么会出现这种情况以及我缺少什么才能使其正常工作? (仅供参考,该代码是由Grant Allen开始的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]);           
        }

    }

}

1 个答案:

答案 0 :(得分:14)

请参阅doc,方法getCheckedItemIds()仅在适配器具有稳定ID时才返回有效结果。相反,你可以使用

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

希望这会帮助你=)