【发布时间】:2020-08-22 04:53:54
【问题描述】:
我正在尝试根据其状态更改SwitchPreference 的图标。如果SwitchPreference 开启,我希望图标设置为@drawable/ic_notifications_active,但如果它关闭,我希望图标设置为@drawable/ic_notifications_off。
这是我在PreferenceScreen xml 文件中的内容:
<SwitchPreference
android:icon="@drawable/ic_notifications_active"
android:key="notifications_switch_preference"
android:defaultValue="true"
app:title="Receive Notifications" />
这就是它在我的设计标签中的样子:
在我的SettingsActivity 中,我有这组代码来检测对SwitchPreference 的更改:
notificationsPreference?.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { preference, newValue ->
val switched: Boolean = (preference as SwitchPreference)
.isChecked
if (switched) {
if (notificationsPreference != null) {
notificationsPreference.icon = resources.getDrawable(R.drawable.ic_notifications_active)
}
} else {
if (notificationsPreference != null) {
notificationsPreference.icon = resources.getDrawable(R.drawable.ic_notifications_off)
}
}
true
}
现在的问题是,当我运行我的应用程序并第一次单击SwitchPreference 切换时,它会将图标的颜色更改为白色,而不是实际的图标。当我再次单击时,它会更改图标,但它仍然是白色的,不再是默认的灰色。现在为错误的状态显示错误的图标。
这是开启和关闭状态的样子:
如何做到这一点,以便当用户单击切换时,它会更改为正确的图标并且不会更改颜色。我也希望它在第一次尝试时工作,而不是在第二次尝试。
【问题讨论】:
-
图标错误的问题可以在没有大量工作的情况下解决,但我还不确定为什么图标的颜色会发生变化。您使用的图标的原始颜色是什么?以下是关于如何更改偏好图标颜色的答案:stackoverflow.com/a/47310452/7210237
标签: android xml kotlin android-preferences switchpreference