我难以从对话框首选项中保留多个值。我有一个DialogPreference,显示两个时间选择器,我希望每个选择器的时间值保持不变(如下所示为startTime和endTime)。但是,我的代码只返回我的DialogPreference中的DefValue,我不明白为什么这些值不会持续存在....感谢您的帮助。代码如下:
public class TimePickerPreference extends DialogPreference implements
TimePicker.OnTimeChangedListener {
private String startTime;
private String endTime;
private String defaultValue;
public TimePickerPreference(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public TimePickerPreference(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
initialize();
}
private void initialize() {
setPersistent(true);
}
@Override
protected View onCreateDialogView() {
LinearLayout layout = new LinearLayout(getContext());
layout.setOrientation(LinearLayout.VERTICAL);
TextView tvStart = new TextView(getContext());
TimePicker tp = new TimePicker(getContext());
TextView tvEnd = new TextView(getContext());
TimePicker tp2 = new TimePicker(getContext());
tvStart.setText("From:");
tvEnd.setText("To:");
tvStart.setTextSize(14);
tvEnd.setTextSize(14);
tp.setOnTimeChangedListener(this);
int h = getHour();
int m = getMinute();
if (h >= 0 && m >= 0) {
tp.setCurrentHour(h);
tp.setCurrentMinute(m);
}
tp.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
final long starttime = (minute * 60 + hourOfDay * 60 * 60) * 1000;
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
startTime = format.format(starttime);
persistString(startTime);
}
});
tp2.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
final long endtime = (minute * 60 + hourOfDay * 60 * 60) * 1000;
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
endTime = format.format(endtime);
persistString(endTime);
}
});
layout.addView(tvStart);
layout.addView(tp);
layout.addView(tvEnd);
layout.addView(tp2);
return layout;
}
答案 0 :(得分:1)
您问题的最佳答案如下:Concise way of writing new DialogPreference classes?
我认为根据该链接存在两个重要错误,首先setPersistent(boolean)
应该为假,其次是您需要使用getEditor()
来存储多个SharedPreferences
DialogPreference
。