1

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

我目前很难做到这一点,我在网上找到了一些东西,比如尝试设置 a MultiChoiceModeListener,但这似乎并没有作为Eclipse. 我正在使用Google APIs(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) { }

        });     
    }       
}
4

3 回答 3

2

稍微更有效/正确:

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));
    }
}
于 2016-06-30T14:57:05.613 回答
1

使用方法getCheckedItemPosition()

于 2012-03-11T08:02:19.340 回答
0

计算 int 中所选项目的计数并进行如下所示的 for 循环。

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 */
   }
}
于 2012-03-11T08:02:54.100 回答