How can I capture when time changes in a TimePicker if the keyboard is being used?

眉间皱痕 提交于 2019-12-04 16:44:53

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.

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);
        }
    }
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!