【问题标题】:How to get checked items from android listview?如何从 android listview 中获取检查项目?
【发布时间】:2015-04-30 23:30:14
【问题描述】:

我有一个使用 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) {

        }
    }

但是我想在启动时将某些项目设置为相对于某个条件已选中。只有当用户选中/取消选中某个项目时才会获得选中的项目。即使项目在以编程方式启动。这里有什么问题?

提前致谢

【问题讨论】:

    标签: android listview checkbox


    【解决方案1】:

    做这样的事情,

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

    【讨论】:

    • 好的。这里我没有手动选择任何项目。即,我没有点击listview items。但是将项目设置为已选中。那么我怎样才能获得选中的项目?
    • @Srujan Simha 不需要 else if 语句,因为这意味着 checkBox 已被选中,请使用 else{...}。此外,这一行给出了错误: cb.remove(position);或者将其编辑为:checkedPositions.remove(position); .我编辑了这个答案,但你不同意,尽管它需要。
    • 我们可以获取已经检查的值并在列表视图中显示它们吗? @Srujan Simha
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多