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

时间:2020-03-24 22:22:08

标签: android kotlin switchpreference

所以我最近参加了Kotlin培训,我有一个片段可以更改我的android应用程序的主题,在成功切换主题后,我使片段重新启动,然后从MainActivity中使用前面设置的捆绑包重新打开该片段。片段。

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

我做错了什么?

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
                }

1 个答案:

答案 0 :(得分:2)

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

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

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

中进行设置
相关问题