Android:输入时如何从 TimePicker 获取时间 [英] Android: How to get the time from a TimePicker when it is typed in

查看:28
本文介绍了Android:输入时如何从 TimePicker 获取时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DialogPreference,它实现了一个简单的 TimePicker.OnTimeChangedListener(见下文).通过单击 +/- 按钮设置时间​​效果很好.但是当用户直接在文本字段中输入时间时,我不知道如何保存时间选择器的状态.访问当前的文本字段值可能就足够了,所以我可以将它保存在 onDialogClosed 中.但是 timePicker.getCurrentHour() 不会这样做.请帮忙...

I've got a DialogPreference which implements a simple TimePicker.OnTimeChangedListener (see below). Setting the time by clicking the +/- buttons works great. But I don't know how to save the state of the timepicker when the user typed in the time directly into the textfield. It could be sufficient to access to the current textfield value, so I'd be able to persist it in onDialogClosed. But timePicker.getCurrentHour() won't do it. 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);
        }
    }
}
// ...
}

推荐答案

直到偶然发现这个问题,我才注意到这个问题.有一个简单的解决方案:当用户在我的应用程序中更改日期和时间后,我只需调用 finish() 并在 onPause() 或 onStop() 或 onDestroy() 中执行以下操作:

I hadn't noticed this problem until i stumbled upon this question. There is a simple solution: When the user is done changing the date and time in my app, i simply call finish() and in the 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();

在此之后,我将 time.toMillis(false) 值存储在表的相应列中.

After this i store the time.toMillis(false) value in the appropriate column of my table.

我不知道时间选择器是否仍然可以在您的 onDialogClosed(boolean positiveResult) 中访问.如果没有,请找到另一个回调以在它仍然存在时使用.

I don't know if the timepicker is still accessible in your onDialogClosed(boolean positiveResult). If not, find another callback to use when it still is.

希望这会有所帮助.

这篇关于Android:输入时如何从 TimePicker 获取时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆