如何检查 SwitchPreference 的当前状态?
How to check the current state of a SwitchPreference?
我有一个 SwitchPreferenceCompat
我想说如果启用了 Switch preference show Toast(启用了 switch preference)否则它再次禁用显示了 Toast(禁用了 switch preference)
有一些这样的问题,但 none 对我有用。
这里是XML:
<PreferenceCategory app:title="عممومی">
<Preference
app:key="backUp"
app:title="بشتیبان گیری آفلاین از اطلاعات" />
<SwitchPreferenceCompat
app:key="vibrate"
app:defaultValue="true"
app:summary="لرزش هنگام انتخاب یک آیتم"
app:title="لرزش" />
</PreferenceCategory>
和设置片段:
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
}
}
myPref!!.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
Toast.makeText(activity, "WORK", Toast.LENGTH_SHORT).show()
true
}
您需要将 onPreferenceClickListener
替换为 onPreferenceChangeListener
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
val myPref = findPreference<SwitchPreferenceCompat>("vibrate")
myPref?.onPreferenceChangeListener =
// The callback is triggered whenever the switch preference is changed
Preference.OnPreferenceChangeListener { pref, newValue ->
if (pref is SwitchPreferenceCompat) {
val value = newValue as Boolean
if (value) Toast.makeText(requireContext(), "WORK", Toast.LENGTH_SHORT)
.show()
else Toast.makeText(requireContext(), "OFF", Toast.LENGTH_SHORT).show()
}
true
}
}
我有一个 SwitchPreferenceCompat
我想说如果启用了 Switch preference show Toast(启用了 switch preference)否则它再次禁用显示了 Toast(禁用了 switch preference)
有一些这样的问题,但 none 对我有用。
这里是XML:
<PreferenceCategory app:title="عممومی">
<Preference
app:key="backUp"
app:title="بشتیبان گیری آفلاین از اطلاعات" />
<SwitchPreferenceCompat
app:key="vibrate"
app:defaultValue="true"
app:summary="لرزش هنگام انتخاب یک آیتم"
app:title="لرزش" />
</PreferenceCategory>
和设置片段:
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
}
}
myPref!!.onPreferenceClickListener = Preference.OnPreferenceClickListener { Toast.makeText(activity, "WORK", Toast.LENGTH_SHORT).show() true }
您需要将 onPreferenceClickListener
替换为 onPreferenceChangeListener
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
val myPref = findPreference<SwitchPreferenceCompat>("vibrate")
myPref?.onPreferenceChangeListener =
// The callback is triggered whenever the switch preference is changed
Preference.OnPreferenceChangeListener { pref, newValue ->
if (pref is SwitchPreferenceCompat) {
val value = newValue as Boolean
if (value) Toast.makeText(requireContext(), "WORK", Toast.LENGTH_SHORT)
.show()
else Toast.makeText(requireContext(), "OFF", Toast.LENGTH_SHORT).show()
}
true
}
}