如何在 Kotlin 中从我的设置 activity 中检索首选项?

How do I retrieve the preferences from my settings activity in Kotlin?

我目前正在为我的学士论文与 Kotlin 作斗争,但我不知道自己在做什么。

所以这是我的问题:

我创建了一个(功能性)设置 activity,其中包含多个 EditTextPreferences 和一个 ListPreference。 现在我想从另一个 activity 的 ListPreference 中检索所选项目。 这是我的 ListPreference:

    <ListPreference
        android:dialogTitle="Art des Implantates"
        android:entries="@array/settings_list_preference_titles"
        android:entryValues="@array/settings_list_preference_values"
        android:key="list"
        android:title="Implantat"
        app:useSimpleSummaryProvider="true"/>

那么如何检索所选项目?假设我只想在其他地方显示它。我什么都不知道,因为我遇到的每一个教程都是针对 java 而我不会说 java.

请帮助我。我很绝望。

第 1 步:为默认首选项获取 SharedPreferences 对象:

val prefs = PreferenceManager.getDefaultSharedPreferences(context)

(其中 contextContext,例如 ActivityApplication 单例)

步骤 #2:在 SharedPreferences 上调用 getString("list", someDefaultValue),其中 "list" 是您的密钥(来自您的 <ListPreference>),someDefaultValueString 如果用户尚未设置此首选项,您希望返回

since every single Tutorial I came across is for java

This sample app (from this book) is in Kotlin and shows the use of SharedPreferences. The documentation 还显示了 SharedPreferences 与 Kotlin(和 Java)的用法。

如果您正在使用 java:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

您可以使用 XML app:key="this_value" 访问值,如下所示:

prefs.getString("this_value","some_val");