getCheckedItemPositions()总是返回null(Android ListView)

时间:2011-09-13 12:50:18

标签: java android listview

编辑:根据问题的演变,我编辑了这个问题。

首先,我知道有一些类似的问题,但每一个都有一个特定的区别,这使得答案对我来说毫无用处......

如果有人能帮助我,我真的很感激,我对这个问题非常绝望......

所以问题是:我想用复选框填充ListView,并且不能使用simple_multiple_choice_mode(类似的东西),因为我需要手动构建我的XML布局 - 所以我使用list_item.xml文件:< / p>

<?xml version="1.0" encoding="utf-8"?>
        <CheckBox 
xmlns:android="http://schemas.android.com/apk/res/android" android:paddingLeft="8mm"
android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:id="@+id/nomeAPP" style="?listItem">
        </CheckBox>

问题是,如果我使用simple_multiple(..)模式选项,getCheckedItemPositions可以正常工作。如果不(如下面的代码中所示)getCheckedItemPositions为null。所以从我读到的,这是一个常见的错误,需要一个处理程序作为解决方法。但我无法让处理程序工作,我在logcat中得到了一个java.lang.NullPointerException异常。

有人可以帮助我吗?

我有这个漂亮的代码:

this.setListAdapter(new ArrayAdapter<String>(this, 
                    R.layout.list_item, aux));

            list.setItemsCanFocus(false);
            list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            list.setSelected(true);
            list.setClickable(true);
            list.setOnItemSelectedListener(new OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    //  Auto-generated method stub

                    Log.d("checked",""+arg2);        


                }

                public void onNothingSelected(AdapterView<?> arg0) {
                    // Auto-generated method stub
                }

            });


            CheckBox c = (CheckBox) findViewById(R.id.nomeAPP);
            c.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                    CheckBox checkbox = (CheckBox)arg0; 
                    boolean isChecked = checkbox.isChecked();

                    if(isChecked == true)
                        Log.v("TAG", "true");
                    else
                        Log.v("TAG", "false");
                }
            });

4 个答案:

答案 0 :(得分:3)

试试这段代码

list = (ListView) findViewById(R.id.listagem);
list.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item,R.id.nomeAPP,aux));
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

//获取这样的选中项目;

int count=list.getChildCount();
for(int i=1;i<=count;i++){
     if(list.isItemChecked(i)){
         //do your task/work
    }
}

答案 1 :(得分:0)

您必须在ListView上设置choiceMode属性才能从此方法获取对象:

http://developer.android.com/reference/android/widget/AbsListView.html#getCheckedItemPositions%28%29

答案 2 :(得分:0)

看起来这是使用setAdapter的一个错误,它使用setListAdapter解决。

让我们看一下,文档说明ListActivity应该使用

list=getListView();
<ListView android:id="@android:id/list"

所以忘了=“+ @ id(....

现在我们的活动可以知道列表中的“where”,现在我们可以使用

setListAdapter(new ArrayAdapter<String>(this, 
                      R.Layout.List_item, aux));

一切正常。

答案 3 :(得分:0)

您的问题是自定义行应该实现Checkable。 阅读this question