简体   繁体   中英

How to change and save switch preference summary

So I recently joined the Kotlin train, and I have a fragment which changes the theme of my android app, I made the fragment restart after successfully switching theme, and then from the MainActivity reopen the fragment using a bundle set earlier in the fragment.

All these work. The problem i'm having is I also tried to change the android:summary field after switching theme, but each time the activity restarts, it switches back to the default summary value

What could I be doing wrong?

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
                }

You can use layout instead: if you want to use two summaries for on and off state of switch preference you can use these properties:

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

But if you want to use Java or Kotlin: summary which is set programmatically will not be saved if you want to keep it you have to set it always in onCreate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM