Hi!
I have a preference screen holding a DialogPreference. When the preference screen comes visible, i want the DialogPreference to have the current time as summary. How can this be achieved? It could be done via xml, but i can't set the current time in the xml file. I tried to set the summary in the onSetInitialValue method, but it doesn't seem to work, as the summary isn't shown.
Here's my code:(In the example below i'm using a string of random text instead of the current time so i don't have to paste the long function that calculates time).
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 ?
}
}
Thank you very much!
In onCreate after addPreferencesFromResource
Preference dialogPref = findPreference(ID for dialog in xml);
dialogPref.setSummary(current time here);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.