【问题标题】:How to save color to SharedPreferences Android如何将颜色保存到 SharedPreferences Android
【发布时间】:2016-09-14 14:59:10
【问题描述】:

我正在尝试将颜色保存到 SharedPreferences 使用

public static void saveChannelImageColor(int color) {
    saveInt(CHANNEL_ID1, color);
}

public static int getChannelImageColor() {
    return getInt(CHANNEL_ID1, 0xff0000ff);
}

但是当我尝试获取颜色时,它给出了错误

java.lang.ClassCastException: java.lang.String 无法转换为 java.lang.Integer 在 android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:239)

【问题讨论】:

  • 您确定,您的颜色值在您的首选项中保存为 int 值吗?因为您的默认值 0xff0000ff 不是整数。
  • 您能否发布相关代码并从 SharedPreferences 中保存和读取?
  • 不要将颜色保存为 int 而是保存为字符串,然后将其作为字符串检索并进行必要的处理。

标签: android


【解决方案1】:

我知道为时已晚,但希望它对某人有所帮助。

Kotlin 代码:

在偏好参考中设置颜色

lateinit var mPreferences: SharedPreferences
lateinit var mEditor: SharedPreferences.Editor   
// initPreferences with Context   

mEditor.putInt(KEY_COLOR_PRIMARY, R.color.colorPrimary)
mEditor.commit()

获取并设置为背景

view.background =  mPreferences.getInt(KEY_COLOR_PRIMARY, 

R.color.colorPrimary))

【讨论】:

    【解决方案2】:

    该错误几乎可以自我解释,您正在为字符串分配一个 int 值。您需要执行以下操作之一

    1. 将颜色保存为字符串

      public static void saveChannelImageColor(int color) {
          saveInt(CHANNEL_ID1, String.valueOf(color));
      }
      
      public static int getChannelImageColor() {
          return getString(CHANNEL_ID1, "0xff0000ff");
      }
      
    2. 无论您在何处使用 getChannelImageColor,它都会返回一个 int,因此您可以将其保存/使用/分配给一个 int 变量。

    【讨论】:

      猜你喜欢
      • 2016-06-23
      • 2016-06-15
      • 1970-01-01
      • 2019-05-28
      • 1970-01-01
      • 2017-11-03
      • 2015-03-22
      • 2011-10-26
      相关资源
      最近更新 更多