user402068
user402068

Reputation: 41

How to get the TimePicker after the TimePickerDialog pop up

I'm working on the android automatic test, and try to test the alarmclock app in the android. I want to get the TimePicker after the TimePickerDialog pop up, then we can use it to invoke the methods 'setCurrentHour(...)' and 'setCurrentMinute()' to set the alarm time programmatically instead of sending the key event so many times. Thank you.

Upvotes: 2

Views: 4280

Answers (3)

Alexandro
Alexandro

Reputation: 11

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

Upvotes: 1

user2730944
user2730944

Reputation:

This may help

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

Upvotes: 1

Pentium10
Pentium10

Reputation: 208042

When onTimeChanged fires at first time, save the View passed in the method. That view will be the reference to TimePicker.

Upvotes: 0

Related Questions