Android: how to get time from TimePicker when it is printed in

I have a DialogPreference that implements a simple TimePicker.OnTimeChangedListener (see below). Setting the time by pressing the +/- buttons works great. But I do not know how to save the timepicker state when the user typed time directly into the text box. It would be enough to access the current value of the text field, so I could save it in onDialogClosed. But timePicker.getCurrentHour () will not do this. Please, help...

public class TimePreference extends DialogPreference implements TimePicker.OnTimeChangedListener { // ... @Override public void onTimeChanged(TimePicker view, int hours, int minutes) { selectedHours = hours; selectedMinutes = minutes; } @Override public void onDialogClosed(boolean positiveResult) { if(positiveResult) { String timeString = selectedHours + ":" + selectedMinutes; if(isPersistent()) { persistString(timeString); } } } // ... } 
+9
android sharedpreferences dialog android-preferences timepicker
Oct 21 '10 at 23:31
source share
2 answers

I did not notice this problem until I came across this question. There is a simple solution: When the user does the date and time change in my application, I just call finish () and in onPause () or onStop () or onDestroy () I do this:

 // force the timepicker to loose focus and the typed value is available ! timePicker.clearFocus(); // re-read the values, in my case i put them in a Time object. time.hour = timePicker.getCurrentHour(); time.minute = timePicker.getCurrentMinute(); 

After that, I save the time.toMillis (false) value in the corresponding column of my table.

I don't know if timepicker is available in your onDialogClosed (boolean positiveResult). If not, find another callback that will be used when it is still there.

Hope this helps.

+46
Nov 09 '10 at 13:53
source share

Only a very bad workaround so far ...

 ViewGroup v = (ViewGroup) timePicker.getChildAt(0); ViewGroup numberPicker1 = (ViewGroup) v.getChildAt(0); ViewGroup numberPicker2 = (ViewGroup) v.getChildAt(1); String hours = ((EditText) numberPicker1.getChildAt(1)).getText().toString(); String mins = ((EditText) numberPicker2.getChildAt(1)).getText().toString(); selectedTime = hours+":"+mins; 
+1
Oct 26 '10 at 17:30
source share



All Articles