gpt4 book ai didi

android - 如何监听 SwitchPreferenceCompat 变化

转载 作者:行者123 更新时间:2023-12-02 13:41:21 31 4
gpt4 key购买 nike

我正在尝试将 onCLick 监听器添加到我的 PreferenceScreen 上的开关,但它不起作用。我尝试了 Java 教程中的代码并将其转换为 Kotlin,但由于某种原因它无法正常工作。

这是我的 AdbSettingsFragment:

package com.wrssmithjr04.systemuituner

import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import android.os.Bundle
import android.util.Log
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat


class AdbSettingsFragment : PreferenceFragmentCompat() {

private val key1 = "adb_switch"

private var preferenceChangeListener: OnSharedPreferenceChangeListener? = null

override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.adb_prefs, rootKey)

preferenceChangeListener =
OnSharedPreferenceChangeListener { sharedPreferences, key ->
if (rootKey == key1) {
Log.d("Test", rootKey)
val adbPref = findPreference<Preference>(key)
// Doesn't get to this part
Log.d("Test", key1 + "was pressed")
}
}
}

override fun onResume() {
super.onResume()
preferenceScreen.sharedPreferences
.registerOnSharedPreferenceChangeListener(preferenceChangeListener)
}

override fun onPause() {
super.onPause()
preferenceScreen.sharedPreferences
.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener)
}

}

感谢您的帮助!

最佳答案

我不知道你为什么要检查 key1rootKey 是否相等。然而,更好的模式是先检查首选项的类型(导致隐式智能转换),然后检查其键:

preferenceChangeListener = OnSharedPreferenceChangeListener { sharedPreferences, key ->
val preference = findPreference<Preference>(key)
when (preference) {
is SwitchPreferenceCompat -> {
if (key == "adb_switch") {
Log.d("Test", "${preference.key} : ${preference.isChecked}")
}
}
is CheckBoxPreference -> {
// do sth else
}
is ListPreference -> {
// do sth else
}
}
}

关于android - 如何监听 SwitchPreferenceCompat 变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63190775/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com