How can I capture when time changes in a TimePicker if the keyboard is being used?
I have a widget which is a TimePicker that retrieves the time saved in a field in a database.
Thing is that when the user changes the time value in the widget, this is not being saved in the database.
So I came across the setOnTimeChangedListener method that works like a charm, if you are only using the plus and minus signs in the widget. It does not capture the change if you are using the keyword.
Here is my code:
pickedTime.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
public void onTimeChanged(TimePicker arg0, int arg1, int arg2) {
System.out.println("What time is it? 开发者_StackOverflow中文版"
+ String.valueOf(arg0.getCurrentHour()) + ":"
+ String.valueOf(arg0.getCurrentMinute()));
}
});
I've also tried unsuccessfully:
pickedTime.setOnFocusChangeListener and pickedTime.setOnKeyListener methods.
It didn't work for me when dealing with a dialog and using the TimePicker.
I read somewhere that it's related to the focus, so if u do a clearFocus right before dismissing the dialog it will work.
Something like:
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
picker.clearFocus();
lastHour=picker.getCurrentHour();
lastMinute=picker.getCurrentMinute();
String time=String.valueOf(lastHour)+":"+String.valueOf(lastMinute);
if (callChangeListener(time)) {
persistString(time);
}
}
}
As mon3t found out, the option is to set android:AddStatesFromChildren="true" in the XML file, as:
<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:addStatesFromChildren="true" />
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:addStatesFromChildren="true" />
Or you can set that by code:
datePicker.setAddStatesFromChildren(true);
timePicker.setAddStatesFromChildren(true);
I really cannot understand what is the point of the default being the way it is.
Sikora's answer is actually adding a lot of value to this common issue.
If you are not managing the change event and look up the value of your time picker from a different piece of code (an onClick handler for a standard button for instance), then the clear focus is needed to get the real value of the time picker when the user manually enters the hours or minutes with the keyboard as opposed to using the up or down arrows or scroller depending on them being on honeycomb or a later version.
Thanks Sikora.
精彩评论