如何检查 SwitchPreference 的当前状态?

汤姆·达里厄斯

我有一个SwitchPreference在我的SettingsFragment.kt改变图标和标题取决于它是否开启或关闭。

这是代码:

notificationsPreference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
    val switched = newValue as? Boolean ?: false
    if (switched) {
        notificationsPreference.icon = ContextCompat.getDrawable([email protected](), R.drawable.ic_notifications_active)
        notificationsPreference.title = "Receive Notifications"
    } else {
        notificationsPreference.icon = ContextCompat.getDrawable([email protected](), R.drawable.ic_notifications_off)
        notificationsPreference.title = "Mute Notifications"
    }
    true
}

但是,此代码有效,假设用户单击SwitchPreference要关闭的,离开SettingsFragment并返回它。它将显示SwitchPreference关闭,但标题和图标将不正确。正确的图标和标题将是我在else上述声明中的代码

如何SwitchPreference在用户输入SettingsFragment. 我想检查一下,如果SwitchPreference关闭,我可以以编程方式设置正确的图标和标题。

赞恩

SwitchPreference保持在当前值SharedPreference使用布尔键/值对。

因此,您可以在PreferenceFragment使用其生命周期方法之一显示时执行此操作,例如onCreatePreferences()

override fun onCreatePreferences(savedInstanceState: Bundle, rootKey: String) {
    setPreferencesFromResource(
        R.xml.settings,  // Your setting.xml file
        rootKey
    ) 
    
    val preference = findPreference(
        getString(R.string.my_preference_key) // Change this to the preference key set in the settings XML file
        val sharedPrefs =
    PreferenceManager.getDefaultSharedPreferences([email protected]())

    // Get the preference value
    val isOn: Boolean = sharedPrefs.getBoolean(
        preference.getKey(),
        false // default value
    )
    
    if (isOn) {
        notificationsPreference.icon = ContextCompat.getDrawable([email protected](), R.drawable.ic_notifications_active)
        notificationsPreference.title = "Receive Notifications"
    } else {
        notificationsPreference.icon = ContextCompat.getDrawable([email protected](), R.drawable.ic_notifications_off)
        notificationsPreference.title = "Mute Notifications"
    }       
    
}

确保更改R.xml.settings为您的设置文件名,以及R.string.my_preference_key首选项键。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何获取javascript websocket连接的当前状态

如何使console.log显示对象的当前状态?

GWT的当前状态如何?

WatchKit如何检查WKInterfaceSwitch的当前状态

如何在DDD中为实体的当前状态建模

如何获得git bisect的当前“状态”?

如何在AWS中检索正在运行的Step Functions的当前状态

如何通过RPC检查流的当前状态?

读取switchpreference的当前值

如何获取Microsoft Teams用户的当前状态

编写功能以检查状态机的当前状态[Lua / Love2d]

如何参考FP中的当前状态?

如何找到请求的当前状态?

如何重置我的重置此应用程序的当前状态

如何知道记录设备的当前状态?

使用Bumblebee时,如何查询nvidia卡的当前状态?

如何将回购的当前状态提交为主控?

如何显示systemd服务的当前服务状态?

如何根据脚本的当前状态自动替换.desktop文件的内容

如何生成迁移以反映数据库的当前状态?

如何将对象的当前状态保存到Servlet的上下文路径或从Servlet的上下文路径获取对象的当前状态

ODOO:如何获取记录对象的当前状态?

打算如何使用SwitchPreference?(ClassCastException)

在多个 Activity 之间传递 ImageButton 的当前图像状态,如何?

如何将本地 git 存储库更新为原始 github 存储库的当前状态?

如何检查 LoginController 中的当前守卫?

刷新后如何保持页面的当前状态?- 反应

更新状态上下文API,如何阻止状态覆盖reducer函数中的当前值?

如何保存html body php的当前状态