【发布时间】:2020-02-04 01:58:13
【问题描述】:
为什么我的ListPreference 没有在偏好更改时执行所需的操作?我关注了this video tutorial,但由于某种原因,监听器无法正常工作。我还没有在 Kotlin 中看到任何关于如何做到这一点的工作教程。
root_preferences.xml
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
<ListPreference
app:defaultValue="reply"
app:entries="@array/reply_entries"
app:entryValues="@array/reply_values"
app:key="list_reply"
app:title="@string/reply_title"
app:useSimpleSummaryProvider="true" />
</PreferenceScreen>
arrays.xml
<resources>
<!-- Reply Preference -->
<string-array name="reply_entries">
<item>Reply</item>
<item>Reply to all</item>
</string-array>
<string-array name="reply_values">
<item>reply</item>
<item>reply_all</item>
</string-array>
</resources>
活动
class SettingsActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.settings_activity)
supportFragmentManager
.beginTransaction()
.replace(R.id.settings, SettingsFragment())
.commit()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
}
}
override fun onDestroy() {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
//...
super.onDestroy()
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
when (key){
"reply" -> {
Toast.makeText(this, "Reply selected", Toast.LENGTH_SHORT).show()
}
"reply_to_all" -> {
Toast.makeText(this, "Reply To All selected", Toast.LENGTH_SHORT).show()
}
}
}
}
【问题讨论】:
-
你在哪里打电话
registerOnSharedPreferenceChangeListener()? -
在
onCreate方法中 -
由于您的
ListPreference键是list_reply,如果您为此添加一个分支到您的when,它会得到控制吗? -
@CommonsWare 我是在分支中添加
when (key)还是when (something else)?
标签: android kotlin android-activity sharedpreferences android-preferences