我想使用NumberPicker首选项。
基本上代码按预期工作。将打开一个带有NumberPicker的对话框。可以选择该值并将其保存到defaulSharedPreferences。
但是第一次启动PreferenceActivity时,默认值未加载,我无法弄清楚原因。
行为是这样的:当我打开PreferenceActivity时,NumberPickerPreference的摘要显示-1。当我关闭Activity并再次重新打开它时,值保持为-1(这与defaultSharedPreferences在存储的键下没有Value一样长)。一旦用户选择了一个值(或者通过键下的代码将值保存到defaultSharedPreferences中),everthing就会起作用,并且在启动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));
}
}
答案 0 :(得分:2)
我遇到了同样的问题。不确定它是否正确但是调用
setDefaultValue(对象);
在Preference构造函数中使用我的默认值似乎解决了这个问题。
答案 1 :(得分:0)
尝试在persistInt(newVal)
之后添加notifyChanged()