简体   繁体   English

Android 自定义首选项值未保存

[英]Android custom preference value not saved

I'm trying to get an existing Preference subclass to work that saves a color value.我正在尝试让现有的 Preference 子类工作以保存颜色值。 I didn't write the class, but it's supposed to be working on android-7 and above (I'm compiling to an android-9 target.) The full source code is available here .我没有编写 class,但它应该适用于 android-7 及更高版本(我正在编译为 android-9 目标。)完整的源代码可在此处获得 Here's where the preference is saved:这是保存首选项的位置:

@Override
public void onColorChanged(int color) {
    if (isPersistent()) {
        boolean ret = persistInt(color);
    }
    // (update preview box, other stuff)
}

Using debug output I can tell that isPersistent() returns true , but persistInt() returns false .使用调试 output 我可以看出isPersistent()返回true ,但persistInt()返回false According to the Android documentation , persistInt() returns whether the preference is persistent;根据Android 文档persistInt()返回首选项是否持久; how can these return different values?这些如何返回不同的值? (Note: setPersistent(true) is explicitly called from the constructor.) (注意: setPersistent(true)是从构造函数中显式调用的。)

In any case, the value is not saved.在任何情况下,都不会保存该值。 A call to getPersistedInt(defaultValue) returns the default value, even later in the same instance of the class.getPersistedInt(defaultValue)的调用会返回默认值,甚至稍后在 class 的同一个实例中。 In the code below, getPersistedInt() is always called and always returns mDefaultValue .在下面的代码中,始终调用 getPersistedInt getPersistedInt()并始终返回mDefaultValue

public int getValue() {
    try {
        if (isPersistent()) {
            mValue = getPersistedInt(mDefaultValue);
        }
    } catch (ClassCastException e) {
        mValue = mDefaultValue;
    }

    return mValue;
}

Why is this, and how can I make sure the preference is persisted?为什么会这样,我怎样才能确保偏好持续存在?

After lots of hopeless searching, I finally found the problem: the preference value was not assigned a key, due to a simple typo in my preferences XML file.经过大量无望的搜索,我终于找到了问题:由于我的偏好 XML 文件中的一个简单的拼写错误,偏好值没有分配一个键。 (I used android.key instead of android:key .) (我用android.key代替android:key 。)

Since Android doesn't warn you when trying to persist a preference that has no key (but silently fails instead,) you should call the shouldPersist() function instead of isPersistent() before trying to persist a value, and perhaps log a warning if shouldPersist() returns false.由于 Android 在尝试保留没有键的首选项时不会警告您(但会默默地失败),因此您应该在尝试保留值之前调用shouldPersist() function 而不是isPersistent() ,并且可能会在以下情况下记录警告shouldPersist()返回错误。 For example:例如:

@Override
public void onColorChanged(int color) {
    mValue = color;
    if (shouldPersist()) {
        persistInt(color);
    } else {
        if (isPersistent())
            Log.w("myapp", "shouldPersist() returned false. Check if this preference has a key.");
    }
    // (update preview box, other stuff)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM