Retrieving the selected items from a multi-select ListView

微笑、不失礼 提交于 2019-12-22 01:36:21

问题


I am currently implementing a multi-select ListView for my android app. My aim is to retrieve the selected items from the ArrayAdapter associated with the ListView when clicking the search button.

I am currently stumped on how to do this, I have found stuff online such as trying to set a MultiChoiceModeListener, but this does not seem to come up as an option in Eclipse. I am using Google APIs(level 10), Android 2.3.3 equivalent. Here is the code I have so far:

   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) { }

        });     
    }       
}

回答1:


Use the method getCheckedItemPosition().




回答2:


Slightly more efficiently / correctly:

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));
    }
}



回答3:


take the count of the selected item in the int and make for loop like below.

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 */
   }
}


来源:https://stackoverflow.com/questions/9653319/retrieving-the-selected-items-from-a-multi-select-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!