Search code examples
androidandroid-layoutandroid-viewandroid-datepicker

Enter elapsed time (some Dialog?)


I need the user to enter the time it took to perform a certain task, for example: 01h: 35mm: 00ss. The format may vary.

Is there something similar to the DatePickerDialog for this task? This way, it could avoid introducing an erroneous format and, above all, it is more elegant and much more comfortable for the user.


Solution

  • Well, there are built-in classes for that. See this code, as a "quick and dirty" example, to pick hours and minutes:

    static boolean bPickedTimeIsValid = false;
    
    public void showTimePicker ()
    {
        bPickedTimeIsValid = false;
    
        DialogFragment newFragment = new TimePickerFragment ();
        newFragment.show (getFragmentManager (), "timePicker");
    }
    
    public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener
    {
        @Override
        public Dialog onCreateDialog (Bundle savedInstanceState)
        {
            // Use the current time as the default values for the picker
            final Calendar c = Calendar.getInstance ();
            int hour = c.get (Calendar.HOUR_OF_DAY);
            int minute = c.get (Calendar.MINUTE);
    
            // Create a new instance of TimePickerDialog and return it
            return new TimePickerDialog (getActivity (), this, hour, minute, DateFormat.is24HourFormat (getActivity ()));
        }
    
        public void onTimeSet (TimePicker view, int hourOfDay, int minute)
        {
            // Time has been chosen by the user, do something with it!
    
            pickedTimeHour = hourOfDay;
            pickedTimeMinutes = minute;
            bPickedTimeIsValid = true;
    
            // Process the picked time as needed...
        }
    }
    

    In your app, you would call showTimePicker() and you would put the code you need to execute when the user picks a time in onTimeSet().

    The maximum duration is limited to one day, of course.