PreferenceManager无法加载自定义首选项的默认值

时间:2016-03-02 11:39:05

标签: android android-preferences android-sharedpreferences

我使用了来自link的TimePreference的代码示例。 与我的问题方法相关:

@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
    Log.v(TAG, "a.getString(index):  " + a.getString(index));
    Log.v(TAG, "hasKey(): " + hasKey() );
    return a.getString(index);
}

@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
    String time=null;

    if (restoreValue) {
        if (defaultValue==null) {
            time=getPersistedString(DEFAULT_NOTIF_TIME_STRING);
        }
        else {
            time=getPersistedString(defaultValue.toString());
        }
    }
    else {
        time=defaultValue.toString();
    }

    lastHour=getHour(time);
    lastMinute=getMinute(time);
}

在notification_time_fragment.xml中:

<mypackage.preferences.TimePreference
    android:key ="@string/notif_time_key"
    android:title="@string/notif_time_title"
    android:defaultValue="08:00"
    android:persistent="true"
    />

活动

PreferenceManager.setDefaultValues(this, R.xml.notification_time_fragment, true);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String notificationTime = sharedPreferences.getString(getString(R.string.notif_time_key), "can't read time");

并且notificationTime等于&#34;无法读取时间&#34;。 从onGetDefaultValue登录:

a.getString(index):  08:00
hasKey(): false

我想来自false的这个hasKey()是我不会通过命令sharedPreference将偏好设置保存在PreferenceManager.setDefaultValues()中的原因。

我必须说使用相同的命令从xml-resource中正确检索android:defaultValue EditTextPreference, CheckBoxPreference

为什么hasKey()false? TimePreference有什么问题?如何在不启动PreferenceActivity且没有&#34;脏编码的情况下使其写入默认值&#34;在MainActivity

0 个答案:

没有答案