2

我有一个SwitchPreferenceCompat,我想说如果启用了切换首选项显示 Toast(启用了切换首选项),否则它再次禁用显示 Toast(禁用了切换首选项) 有一些这样的问题,但没有一个对我有用。

这是 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)
    }
}

相关问题

4

1 回答 1

2
myPref!!.onPreferenceClickListener =
    Preference.OnPreferenceClickListener {
        Toast.makeText(activity, "WORK", Toast.LENGTH_SHORT).show()
        true
    }

您需要替换onPreferenceClickListeneronPreferenceChangeListener

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
        }
}
于 2021-11-03T13:54:09.093 回答