如何使用simple_list_item_checked保存和恢复选中的项目?

时间:2015-12-09 10:52:37

标签: android listview checked

我想知道保存和恢复已检查项目的最佳方法,在适配器上使用“simple_list_item_checked”,我一直在尝试使用SharedPreferences很长时间,但是没有用。你能举个例子吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

在这里,找到了我的旧代码。您可以使用SparseBooleanArray

private SparseBooleanArray sbArray;

//set all of the items checked in the start
            if (sbArray == null) {
                for (int i = 0; i < listView.getCount(); i++) {
                    listView.setItemChecked(i, true);
                }
            }
            selectedIdees = new ArrayList<>();

    //if we already did some checking in filters, we get our previous selections.
            if (sbArray != null) {
                Log.i(LOG_TAG, "sbArray size " + sbArray.size());

                for (int i = 0; i < sbArray.size(); i++) {
                    int key = sbArray.keyAt(i);
                    if (sbArray.get(key)) {
                        listView.setItemChecked(key, true);
                    }

然后在某处我放置了okButton并将onClickListener设置为它。

okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                sbArray = listView.getCheckedItemPositions();

                Log.i(LOG_TAG, "sbArray created. size= " + sbArray.size());
                for (int i = 0; i < sbArray.size(); i++) {
                    int key = sbArray.keyAt(i);

                    if (sbArray.get(key)) {
                        selectedIdees.add(key + 1);
                        Log.i(LOG_TAG, "added + " + (key + 1));
                    }

然后我建议将其保存在共享首选项中,创建parcelable wrapper around it