如何从android listview获取检查项目?

时间:2013-02-27 11:16:46

标签: android listview checkbox

我有一个使用listview的Android应用程序。每一行包含ImageView,TextView和CheckBox。 我想从这个listview中获取所选项目。我使用了

private void getSelectedItems() {
        List<String>list = new ArrayList<String>();
        try {
            SparseBooleanArray checkedItems = new SparseBooleanArray();
            checkedItems = listView.getCheckedItemPositions();
            if (checkedItems == null) {
                return;
            }
            final int checkedItemsCount = checkedItems.size();
            for (int i = 0; i < checkedItemsCount; ++i) {
                int position = checkedItems.keyAt(i);
                boolean bool = checkedItems.valueAt(position);
                if (bool) {
                   list.add(mainList.get(position));
                }
            }

        } catch (Exception e) {

        }
    }

但是我想在启动条件下设置一些检查项目。只有当用户检查/取消选中项目时,才会获得检查项目。即使项目设置为已选中以编程方式启动。这里有什么问题?

先谢谢

1 个答案:

答案 0 :(得分:3)

做这样的事,

ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
myListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view,
                    int position, long arg3) {
                CheckBox cb = (CheckBox) view.findViewById(R.id.yourCheckBox);
                Toast.makeText(getApplicationContext(), "Row " + position + " is checked", Toast.LENGTH_SHORT).show();
                if (cb.isChecked()) {
                    checkedPositions.add(position); // add position of the row
                                                    // when checkbox is checked
                } else {
                    checkedPositions.remove(position); // remove the position when the
                                            // checkbox is unchecked
                    Toast.makeText(getApplicationContext(), "Row " + position + " is unchecked", Toast.LENGTH_SHORT).show();
                }
            }
        });