当前位置: 代码迷 >> Android >> 弹出TimePickerDialog后如何获取TimePicker
  详细解决方案

弹出TimePickerDialog后如何获取TimePicker

热度:29   发布时间:2023-08-04 12:17:18.0

我正在进行android自动测试,并尝试在android中测试闹钟应用。 我想在弹出TimePickerDialog之后获取TimePicker,然后我们可以使用它来调用方法'setCurrentHour(...)'和'setCurrentMinute()'来以编程方式设置警报时间,而不是多次发送按键事件。 谢谢。

这可能会有所帮助

    Calendar mCalendar = Calendar.getInstance();

     mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
     mMinute = mCalendar.get(Calendar.MINUTE);


     TimePickerDialog timePickerDialog = new TimePickerDialog(mActivity, mTimeSetListener, mHour, mMinute, false);

     private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
         public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

             mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
         mCalendar.set(Calendar.MINUTE, mMinute);
         SimpleDateFormat mSDF = new SimpleDateFormat("hh:mm a");
         String time = mSDF.format(mCalendar.getTime());
     }
 }

首次启动onTimeChanged时,保存在方法中传递的View。 该视图将作为对TimePicker的引用。

public class CustomTimePickerDialog extends TimePickerDialog {

    public CustomTimePickerDialog(Context context, OnTimeSetListener listener, int hourOfDay, int minute, boolean is24HourView) {

        super(context, listener, hourOfDay, minute, is24HourView);
        try {
            Class<?> superClass = getClass().getSuperclass();
            Field TimePickerField = superClass.getDeclaredField("mTimePicker");
            TimePickerField.setAccessible(true);
            TimePicker timePicker = (TimePicker) TimePickerField.get(this);
            timePicker.setOnTimeChangedListener(this);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public int getHour() {
        return currentHour;
    }

    public int getMinute() {
        return currentMinute;
    }

    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {

        super.onTimeChanged(view, hourOfDay, minute);
        currentHour = hourOfDay;
        currentMinute = minute;
    }

    private int currentHour;
    private int currentMinute;
}