3

我有一个使用 listview 的 android 应用程序。每行由 ImageView、一个 TextView 和一个 CheckBox 组成。我想从此列表视图中获取选定的项目。我用过

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

        }
    }

但是我想在启动时将某些项目设置为针对某个条件进行检查。仅当用户选中/取消选中某个项目时才会获得选中的项目。即使在启动时以编程方式将项目设置为选中,也不会获得选中的项目。这里有什么问题?

提前致谢

4

1 回答 1

3

Do something like this,

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();
                }
            }
        });
于 2013-02-27T11:37:29.893 回答