如何更改和保存开关首选项摘要

How to change and save switch preference summary

所以我最近加入了 Kotlin train,我有一个 fragment 改变了我的 android 应用程序的主题,我在成功切换主题后重新启动了 fragment,然后从 MainActivity 重新打开 fragment 使用片段中较早设置的捆绑包。

所有这些工作。我遇到的问题是我也尝试在切换主题后更改 android:summary 字段,但每次 activity 重新启动时,它都会切换回默认摘要值

我可能做错了什么?

SettingsFragment.kt

       findPreference(getString(R.string.key_dark_theme)).setOnPreferenceChangeListener { preference, newValue ->
                    preference.isEnabled = false
                    val switchPreference = preference as SwitchPreference
                    val intent = activity!!.intent
                    val tempBundle = Bundle()
                    intent.putExtra("bundle", tempBundle)

                    Thread {
                        val changeTheme = newValue as Boolean

                        try {
                            activity!!.runOnUiThread {
                                switchPreference.isChecked = changeTheme
                                switchPreference.summary = "On" //this clears once I restart the activity
                                activity!!.finish()
                                activity!!.startActivity(intent)
                                activity!!.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out)
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }

                        activity!!.runOnUiThread {
                            switchPreference.isEnabled = true
                        }
                    }.start()
                    false
                }

您可以改用布局:如果您想对开关首选项的打开和关闭状态使用两个摘要,您可以使用这些属性:

<SwitchPreference
            android:summaryOff="@string/summary_off"
            android:summaryOn="@string/summary_on" />

但是如果你想使用 Java 或 Kotlin: 以编程方式设置的摘要将不会被保存 如果您想保留它,则必须始终将其设置为 onCreate