自定义DialogPreference的默认值为null

时间:2014-07-28 21:28:50

标签: android android-preferences

我有一个TimePreference类派生自DialogPreference。我使用3 NumberPicker来设置小时,分钟和秒。这很好用。但是,onSetInitialValue被调用defaultValue始终是null。而onGetDefaultValue返回首选项中定义的正确值。有什么想法是错的吗?

public TimePreference(Context ctxt, AttributeSet attrs, int defStyle) {
    super(ctxt, attrs, defStyle);

    setPositiveButtonText(R.string.ok);
    setNegativeButtonText(R.string.cancel);
    setDialogLayoutResource(R.layout.time_preference_layout);
}

@Override
protected void onBindDialogView(View v) {
    super.onBindDialogView(v);

    mHoursPicker = (NumberPicker)v.findViewById(R.id.hours);
    mHoursPicker.setMinValue(0);
    mHoursPicker.setMaxValue(23);
    mHoursPicker.setFormatter(TWO_DIGIT_FORMATTER);

    mMinutesPicker = (NumberPicker)v.findViewById(R.id.minutes);
    mMinutesPicker.setMinValue(0);
    mMinutesPicker.setMaxValue(59);
    mMinutesPicker.setFormatter(TWO_DIGIT_FORMATTER);

    mSecondsPicker = (NumberPicker)v.findViewById(R.id.seconds);
    mSecondsPicker.setMinValue(0);
    mSecondsPicker.setMaxValue(59);
    mSecondsPicker.setFormatter(TWO_DIGIT_FORMATTER);
}

@Override
protected void onDialogClosed(boolean positiveResult) {
    super.onDialogClosed(positiveResult);

    if (positiveResult) {
        long currentTimeInMillis = convertTimeToMillis();

        if (callChangeListener(currentTimeInMillis)) {
            persistLong(currentTimeInMillis);
            notifyChanged();
        }
    }
    CharSequence summary = getSummary();
    setSummary(summary);
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
    super.onGetDefaultValue(a, index);
    return a.getString(index);
}

@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
    super.onSetInitialValue(restoreValue, defaultValue);

    long value = 0;

    if (restoreValue) {
        if (defaultValue == null) {
            Log.d( "bla", "No default value defined!");
        } else {
            value = Long.parseLong(getPersistedString((String) defaultValue));
        }
    } else {
        if (defaultValue == null) {
            Log.d( "bla", "No default value defined!");
        } else {
            value = Long.parseLong((String) defaultValue);
        }
    }

    String result = convertMillisToTime(value);
    setSummary(result);
}


@Override
public CharSequence getSummary() {
    if (mHoursPicker == null) {
        return null;
    }
    return convertTimeToString( mHoursPicker.getValue(), mMinutesPicker.getValue(), mSecondsPicker.getValue());
}

}

1 个答案:

答案 0 :(得分:0)

为什么不尝试手动设置默认值?如果要将此时间值保存到sharedPreferences,则可以在PreferenceScreen的xml声明中指定它:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <PreferenceCategory
        android:title="@string/pref_cat_general"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <to.marcus.rxtesting.ui.widgets.ChoicePreference
            android:key="@string/pref_key_sel_time"
            android:title="@string/pref_title_time"
            android:summary="set time"/>

请注意自定义偏好 ChoicePreference 。声明后,您可以在自己的类中定义它,类似于您通过扩展DialogPreference所做的事情:

public class ChoicePreference extends DialogPreference {
    public ChoicePreference(Context context, AttributeSet attrs){
        super(context,attrs);
    }

    @Override
    protected void onClick(){
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        dialog.setTitle("Check Time");
        dialog.setMessage("confirm time:");
        dialog.setCancelable(true);
        dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getContext(), "time set!",    Toast.LENGTH_SHORT).show();
                putPrefValue("key_sel_time",true);
            }
        });

putPrefValue(键,值)方法将写入/覆盖您的sharedPreference值:

private void putPrefValue(String key, boolean value){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
    SharedPreferences.Editor editor = prefs.edit();
    //removes existing key to trigger change listener
    editor.remove(key);
    editor.commit();
    editor.putBoolean(key, value);
    editor.apply();
}

然后从这一点开始,您需要使用您的Activity来收听这些sharedPreference更改:

1。)为sharedPrefs设置一个监听器变量:

    private static SharedPreferences sharedPrefs;
    private static SharedPreferences.OnSharedPreferenceChangeListener mListener;

2。)注册/取消注册听众

@Override
protected void onResume() {
    super.onResume();
    sharedPrefs.registerOnSharedPreferenceChangeListener(mListener);
}

@Override
protected void onPause() {
    super.onPause();
    sharedPrefs.unregisterOnSharedPreferenceChangeListener(mListener);
}

3。)获取一个实例,并对结果/更改

执行某些操作
 private void initSharedPrefsListener(){
        sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        mListener = new SharedPreferences.OnSharedPreferenceChangeListener(){
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPrefs, String key){
                mBasePresenterImpl.onPrefSelected(key, sharedPrefs.getString(key, "default value here"));
        }
    };
}

这里的 onPrefSelected 方法是概念性的。您可以获取结果值并将其持久保存到JsonString。