如何从 ListView 中获取所有选中的项目? [英] How to get all checked items from a ListView?

查看:31
本文介绍了如何从 ListView 中获取所有选中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个问题没弄明白.

I've a couple of question I haven't been able to figure out.

我正在尝试从 ListView 中获取所有选中的元素,但是:

I'm trying to get all the checked elements from a ListView but:

  1. 如果我选中然后取消选中一个元素,它会被 getCheckedItemPositions() 函数返回为已选中"

我不知道如何遍历这个:

I don't know how can I iterate through this:

SparseBooleanArray checked = list.getCheckedItemPositions();

推荐答案

我用这个解决了我的问题:

I solved my case with this:

public class MyAdapter extends BaseAdapter{
    public HashMap<String,String> checked = new HashMap<String,String>();
....
    public void setCheckedItem(int item) {


        if (checked.containsKey(String.valueOf(item))){
            checked.remove(String.valueOf(item));
        }

        else {
            checked.put(String.valueOf(item), String.valueOf(item));
        }
    }
        public HashMap<String, String> getCheckedItems(){
        return checked;
    }
}

要设置一个元素被选中:

To set an element is checked:

public class FileBrowser extends Activity implements OnClickListener{        
private ListView list;

    ...
    list.setOnItemClickListener(new OnItemClickListener(){

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int item,
                long id) {

                        BrowserAdapter bla = (BrowserAdapter) parent.getAdapter();
                        bla.setCheckedItem(item);
                    }
    });

然后从课外拿到选中的物品..

Then to get the checked items from outside the class..

MyAdapter bAdapter;    
Iterator<String> it = bAdapter.getCheckedItems().values().iterator();
                    for (int i=0;i<bAdapter.getCheckedItems().size();i++){
                        //Do whatever
                        bAdapter.getItem(Integer.parseInt(it.next());
                    }

希望它可以帮助某人.

这篇关于如何从 ListView 中获取所有选中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆