我想使用 NumberPicker 首选项。
基本上代码按预期工作。一个带有 NumberPicker 的对话框打开。可以选择该值并将其保存到 defaulSharedPreferences。
但是在第一次启动 PreferenceActivity 时,默认值没有加载,我不知道为什么。
行为是这样的:当我打开 PreferenceActivity 时,NumberPickerPreference 的摘要显示-1。当我关闭 Activity 并再次重新打开它时,值保持在 -1 (只要 defaultSharedPreferences 在存储的键下没有值)。一旦用户选择了一个值(或者一个值通过键下的代码保存到 defaultSharedPreferences 中),一切都会起作用,并且在 PreferenceActivity 启动时加载该值。
public class NumberPickerPreference extends DialogPreference implements NumberPicker.OnValueChangeListener
{
private static final String NAMESPACE="http://schemas.android.com/apk/res/android";
private NumberPicker mNumberPicker;
private TextView mTvDialogMessage;
private Context mCtx;
private String mDialogMessage;
private int mDefault;
private int mMax;
private int mValue = 0;
public NumberPickerPreference(Context ctx, AttributeSet attr) {
super(ctx, attr);
mCtx = ctx;
//Get XML attributes
mDialogMessage = attr.getAttributeValue(NAMESPACE,"dialogMessage");
mDefault = attr.getAttributeIntValue(NAMESPACE,"defaultValue", 2);
mMax = attr.getAttributeIntValue(NAMESPACE,"max", 20);
}
@Override
protected View onCreateDialogView() {
//Create Views
LinearLayout dialogLayout = new LinearLayout(mCtx);
mTvDialogMessage = new TextView(mCtx);
mNumberPicker = new NumberPicker(mCtx);
//Set View attributes
dialogLayout.setOrientation(LinearLayout.VERTICAL);
if (mDialogMessage!=null)
mTvDialogMessage.setText(mDialogMessage);
dialogLayout.addView(mTvDialogMessage);
mNumberPicker.setOnValueChangedListener(this);
dialogLayout.addView(mNumberPicker, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
if (shouldPersist())
mValue = getPersistedInt(mDefault);
mNumberPicker.setMaxValue(mMax);
mNumberPicker.setMinValue(1);
mNumberPicker.setValue(mValue);
return dialogLayout;
}
@Override
protected void onBindDialogView(View v) {
super.onBindDialogView(v);
mNumberPicker.setMaxValue(mMax);
mNumberPicker.setMinValue(1);
mNumberPicker.setValue(mValue);
setSummary(mValue);
}
@Override
protected void onSetInitialValue(boolean restore, Object defaultValue)
{
super.onSetInitialValue(restore, defaultValue);
if (restore)
mValue = shouldPersist() ? getPersistedInt(mDefault) : 2;
else
mValue = (Integer)defaultValue;
if (mNumberPicker!=null)
mNumberPicker.setValue(mValue);
setSummary(mValue);
}
public void setSummary(int value) {
CharSequence summary = getSummary();
value=getPersistedInt(-1);
if (summary == null) {
setSummary(Integer.toString(value));
} else {
setSummary(String.format(summary.toString(), value));
}
}
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
setSummary(newVal);
if (shouldPersist())
persistInt(newVal);
callChangeListener(new Integer(newVal));
}
}