I wanted to implement a method picking a time and returning it, something like
public static int pickTime(Context context, int minuteOfDay) {
final int[] result = {-1};
final OnTimeSetListener listener = new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) {
result[0] = 60*hourOfDay + minute;
}
};
new MyTimePickerDialog(context, listener, minuteOfDay/60, minuteOfDay%60, false).show();
return result[0];
}
only to find out that the dialog returns immediately, and thus my method always return -1.
That’s something I can live with, however, I’m curious if something like this is possible. I don’t care if the app works while waiting for the input, as the TimePicker takes nearly the whole screen anyway.
Note that the standard solution works for me, but I consider this to be a good an exercise for better understanding of the system.
It’s easily possible from another thread, just wait for the dialog to close. From the main Thread waiting doesn’t work, as it blocks the events processing. So instead of waiting I’d have to run the event loop myself, which might be complicated or even impossible.
What could be done is passing a
TextView, which should be set. However, I always need to do more, so it’s quite useless. I ended up with a class which can be used as follows (invoking the constructor does the whole work):