class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
}
}
root_preferences
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceCategory app:title="@string/language_setting_header">
<ListPreference
app:defaultValue="en"
app:entries="@array/language_entries"
app:entryValues="@array/language_values"
app:key="@string/key_lang"
app:title="@string/language_setting_title"
app:useSimpleSummaryProvider="true" />
</PreferenceCategory>
for
onPreferenceTreeClick
Only trig when show the dialog but not trig on each item in ListPreference
Instead of listen to each item of the list
Listen when prefChange. Also registListener onResume and onPause
Solution in Kotlin for PreferenceFragmentCompat
class SettingsFragment : PreferenceFragmentCompat() {
private val prefListener = SharedPreferences.OnSharedPreferenceChangeListener { prefs, key ->
when (key) {
"lang" -> {
activity?.finish()
}
}
}
override fun onResume() {
super.onResume()
preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(
prefListener
)
}
override fun onPause() {
preferenceManager.sharedPreferences.unregisterOnSharedPreferenceChangeListener(
prefListener
)
super.onPause()
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(
prefListener
)
}
}
https://developer.android.com/reference/androidx/preference/PreferenceFragmentCompat