Я пытаюсь создать страницу настроек, которая позволяет пользователю изменять тему приложения, но по какой-то причине элементы управления не ведут себя так, как они должны:
- приложение застревает на темной теме все время после нажатия на
RadioButton
- Тема действительно применяется, но оба
RadioButton
s по какой-то причине проверяются
Деятельность
class SettingsActivity : AppCompatActivity(), SettingsFragment.PreferenceXchangeListener {
// Initial value for applying appropriate theme
private var mCurrentValue: Boolean = false // False is default value
override fun onCreate(savedInstanceState: Bundle?) {
// Check which theme should be used. IMPORTANT: applying Themes MUST called BEFORE super.onCreate() and setContentView!!!
val mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
mCurrentValue = mSharedPreferences.getBoolean("boosted", false)
if (mCurrentValue) {
setTheme(R.style.MyDarkSettingsTheme)
} else {
setTheme(R.style.MyLightSettingsTheme)
}
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
val viewllSettingsContainer = settings_container
val root = viewllSettingsContainer.rootView
if (mCurrentValue) {
root.setBackgroundColor(Color.BLACK)
} else {
root.setBackgroundColor(Color.WHITE)
}
val settingsFragment = SettingsFragment()
supportFragmentManager
.beginTransaction()
.replace(R.id.settings_container, settingsFragment)
.commit()
}
// Callback method for changing preference. It's only called if "preference_a" has changed
override fun onXchange(value:Boolean) {
// If value differs from previous Theme, recreate Activity
when {
mCurrentValue != value -> {
mCurrentValue = value
recreate()
}
}
}
}
Фрагмент
class SettingsFragment : PreferenceFragmentCompat(), Preference.OnPreferenceChangeListener,
Preference.OnPreferenceClickListener {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.app_preferences)
findPreference<RadioButtonPreference>("light")?.apply {
updateCheckedRadioButton(this)
onPreferenceClickListener = this@SettingsFragment
}
findPreference<RadioButtonPreference>("dark")?.onPreferenceClickListener = this
}
// Declaring PreferenceXchangeListener
private var mPreferenceXchangeListener: PreferenceXchangeListener? = null
// Declare PreferenceXchangeListener to communicate with Activities
interface PreferenceXchangeListener {
fun onXchange(value:Boolean)
}
override fun onAttach(context: Context) {
super.onAttach(context)
// On attach - assign parent Activity as PreferenceXchangeListener
try
{
mPreferenceXchangeListener = context as PreferenceXchangeListener
}
catch (e:ClassCastException) {
Log.e(TAG, "onAttach::::: PreferenceXchangeListener must be set in parent Activity")
}
}
override fun onPreferenceChange(preference: Preference, newValue:Any):Boolean {
return if (preference.key == "dark") {
(preference as RadioButtonPreference).isChecked = newValue as Boolean
// Execute parent Activity's callback with the new value
mPreferenceXchangeListener!!.onXchange(newValue)
true
}
// check other preferences here
else false
}
private var oldCheckedPreference: RadioButtonPreference? = null
private fun updateCheckedRadioButton(radioButtonPreference: RadioButtonPreference) {
// Uncheck the previous selected RadioButton if necessary.
oldCheckedPreference?.isChecked = false
radioButtonPreference.isChecked = true
oldCheckedPreference = radioButtonPreference
}
override fun onPreferenceClick(preference: Preference): Boolean {
if (preference is RadioButtonPreference)
updateCheckedRadioButton(preference)
if (preference.key == "dark")
activity!!.setTheme(R.style.DarkTheme)
activity!!.recreate()
else
activity!!.setTheme(R.style.LightTheme)
activity!!.recreate()
return true
}
companion object {
private val TAG = SettingsFragment::class.java.simpleName
}
}
xml / app_preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Application theme">
<com.companyname.appname.RadioButtonPreference
android:key="light"
android:title="Light" />
<com.companyname.appname.RadioButtonPreference
android:key="dark"
android:title="Dark" />
</PreferenceCategory>
</PreferenceScreen>
anim / fade.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="1.0" android:toAlpha="0.0"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
Текущий результат