你好!
我有一个包含 DialogPreference 的首选项屏幕。当首选项屏幕可见时,我希望 DialogPreference 将当前时间作为摘要。如何做到这一点?它可以通过 xml 完成,但我无法在 xml 文件中设置当前时间。我尝试在 onSetInitialValue 方法中设置摘要,但它似乎不起作用,因为未显示摘要。
这是我的代码:(在下面的示例中,我使用一串随机文本而不是当前时间,因此我不必粘贴计算时间的长函数)。
public class TimePreference extends DialogPreference {
private TimePicker timePicker;
Calendar calendar = Calendar.getInstance();
private int hour = calendar.get(Calendar.HOUR_OF_DAY);
private int minute = calendar.get(Calendar.MINUTE);
public TimePreference(Context context, AttributeSet attributes) {
super(context, attributes);
setPersistent(false);
//setSummary(getFormatedTime(hour, minute));
}
/**
* Initialize time picker to currently stored time preferences.
*
* @param view
* The dialog preference's host view
*/
@Override
public void onBindDialogView(View view) {
super.onBindDialogView(view);
timePicker = (TimePicker) view.findViewById(R.id.time_picker);
timePicker.setIs24HourView(DateFormat.is24HourFormat(timePicker.getContext()));
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(minute);
}
/**
* Handles closing of dialog. If user intended to save the settings, selected
* hour and minute are stored in the preferences with keys KEY.hour and
* KEY.minute, where KEY is the preference's KEY.
*
* @param okToSave
* True if user wanted to save settings, false otherwise
*/
@Override
protected void onDialogClosed(boolean okToSave) {
super.onDialogClosed(okToSave);
if (okToSave) {
timePicker.clearFocus();
SharedPreferences.Editor editor = getEditor();
hour = timePicker.getCurrentHour();
minute = timePicker.getCurrentMinute();
editor.putInt(getKey() + ".hour", hour);
editor.putInt(getKey() + ".minute", minute);
editor.commit();
setSummary(getFormatedTime(hour, minute));
}
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
super.onSetInitialValue(restoreValue, defaultValue);
setSummary("current time here!"); // THIS IS NEVER SHOWN ?? WHY ?
}
}
非常感谢!