在 ListView 中保留项目的选中状态

Persist checked status of items in ListView

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

检查其中一项后,它应保持检查状态,直到检查另一项,或直到用户 'stops' 来自通知或 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
    }
});

当您 select 列表项时,您可以看到在我的其他 activity 打开之前正在检查该项目。但是,当我 return 到主 activity 时,不再检查任何项目。

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

列表视图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" />

CheckedTextViewxml:

<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" />

您可以将选中的项目存储在 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)时返回的默认值。

之后,您可以在每次创建列表 activity 时手动将项目标记为选中。

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

有关详细信息,您可以阅读 SharedPreferences 和 PreferenceManager 文档。

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

首选项管理器https://developer.android.com/reference/android/preference/PreferenceManager

希望对您有所帮助。

我会在列表中的所有对象中多一个字段。它可以是布尔值检查,默认为 false,当它被点击时使其为真。然后你可以很容易地保存对象的状态。如果您更改状态,只需通知适配器它应该重绘自己。