从多选ListView中检索所选项

时间:2012-03-11 07:46:53

标签: android android-listview android-sdk-2.3 multiple-select

我目前正在为我的Android应用程序实现多选ListView。我的目的是在点击搜索按钮时从与ArrayAdapter相关联的ListView中检索所选项目。

我目前对如何执行此操作感到困惑,我已经在网上找到了诸如尝试设置MultiChoiceModeListener之类的内容,但这似乎并没有在Eclipse中作为选项出现。我正在使用Google API s(级别10),Android 2.3.3等效。这是我到目前为止的代码:

   public class FindPlace extends Activity {    

    public FindPlace() {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {            
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_places);
        Button search = (Button) findViewById(R.id.search);
        String[] categories = getResources().getStringArray(R.array.Categories);
        ArrayAdapter ad = new ArrayAdapter(this,android.R.layout.simple_list_item_multiple_choice,categories);
        final ListView list=(ListView)findViewById(R.id.List);
        list.setAdapter(ad);
        list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) { }

        });     
    }       
}

3 个答案:

答案 0 :(得分:1)

使用方法getCheckedItemPosition()

答案 1 :(得分:1)

稍微高效/正确:

SparseBooleanArray checked = listView.getCheckedItemPositions();
for (int i = 0; i < checked.size(); ++i)
{
    if (checked.valueAt(i))
    {
        int pos = checked.keyAt(i);
        doSomethingWith(adapter.getItem(pos));
    }
}

答案 2 :(得分:0)

获取int中所选项目的计数,并按如下所示进行循环。

int len = listView.getCount();
SparseBooleanArray checked = listView.getCheckedItemPositions();
for (int i = 0; i < len; i++){
if (checked.get(i)) {
       String item = cont_list.get(i);
       /* do whatever you want with the checked item */
   }
}