在ListView中保留已检查项目的状态

时间:2018-05-12 14:59:20

标签: java android listview android-activity android-checkedtextview

我有ListViewCheckedTextView个项目,每个项目都使用一个单选按钮。它是一个单选列表,表示我的主要活动中正在播放的音频流。

一旦检查了其中一个项目,它应该保持检查状态,直到检查了另一个项目,或者直到用户“停止”来自通知或UI的流,并且每次退出应用程序时都需要重置检查状态

我正在做的那一刻:

final BookmarkAdapter adapter = new BookmarkAdapter(this, db.getAllBookmarks());
final ListView listView = findViewById(R.id.bookmark_list_view);

listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        View v = listView.getChildAt(position);
        CheckedTextView ctv = v.findViewById(R.id.bookmark_list_item);
        ctv.toggle();
        // ... go on to launch a service and another activity
    }
});

在我打开其他活动之前,您可以看到在选择列表项时正在检查项目。但是,当我返回主活动时,不再检查任何项目。

在关闭应用程序或手动取消选中之前,持久检查项目状态的正确方法是什么?

ListView xml:

<ListView
        android:id="@+id/bookmark_list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:choiceMode="singleChoice"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

CheckedTextView xml:

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/bookmark_list_item"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/listPreferredItemHeight"
        android:checkMark="?android:attr/listChoiceIndicatorSingle"
        android:gravity="center_vertical"
        android:paddingLeft="16dip"
        android:paddingRight="16dip"
        android:text="@string/list_item_title"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

2 个答案:

答案 0 :(得分:1)

您可以将选中的项目存储在SharedPreferences中。 SharedPreferences是由应用程序上下文管理的配置文件中的简单存储。最好的是,即使应用程序被关闭或被杀,它仍然存在。

每个应用程序都有自己的SharedPreferences文件存储在其上下文文件目录中(存储在磁盘中)。

要存储持久值,您可以编写以下内容:

SharedPreferences prefs =  PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putInt("checked_item", position).apply();

然后,您可以通过以下方式检索存储的已检查项目位置:

int checkedPosition = prefs.gerInt("checked_item", 0);

0,如果没有存储密钥(checked_item),则返回默认值。

之后,您可以在每次创建列表活动时手动将项目标记为已检查。

您可以将项目位置存储在onItemClick()中,然后您可以检索它并在活动中的onCreate()或onResume()中标记为已选中。

有关详细信息,请阅读SharedPreferences和PreferenceManager文档。

SharedPreferences https://developer.android.com/reference/android/content/SharedPreferences

PreferenceManager https://developer.android.com/reference/android/preference/PreferenceManager

希望这有帮助。

答案 1 :(得分:1)

我在列表中的所有对象中还有一个字段。它可以是布尔检查的,默认为false,当它被点击时使其成立。然后你可以轻松保存对象的状态。如果你改变状态,只需通知适配器它应该重绘自己。