android - 如何从android listview中获取选中的项目?

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

        }
    }

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

提前致谢

最佳答案

做这样的事情,

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

关于android - 如何从android listview中获取选中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15110724/

相关文章:

php - 2 或 3 类别搜索复选框 php

android - 向可搜索 ListView 中的项目添加 Intent

javascript - Gmail 中的多个复选框检查

android - 同时构建许多类似的 Android .apk 文件?

java - Android studio - 带Retrofit2的外汇汇率API,无法运行应用程序

c# - 从 TextBlock MouseDown 获取 DataContext

android - ListView 底部的 TextView - api 7

javascript - 根据复选框状态启用/禁用输入字段

android - Gradle同步在Android Studio 3.6中失败

java - 从 Activity 向 Intent 传递附加值会抛出 NullPointerException