Parameters:
context - Parent.
callBack - How parent is notified.
hourOfDay - The initial hour.
minute - The initial minute.
is24HourView - Whether this is a 24 hour view, or AM/PM.
is24HourView set to true |
1. In the MainActivity.java file, Declare a TimePickerDialog object named myTimePickerDialog in a private method with a return value, with the method named showTimePicker and and return value type of TimePickerDialog.
2. Also, add the below import to the imports section.
import android.widget.TimePicker;
3. Add the below code to the showTimePicker method. This will set the TimePickerDialog and initialize the hour and minute to 3, 54, and true respectively. This will display the time of 3 hours, 54 minutes, in 24 hour time(without an AM/PM button). If it is set to false, the time will be in 12 hour format and the AM/PM button will display. Adding a toast will display the hour, minute, and AM/PM the user selected in the TimePickerDialog. This below would be in a class named MyClassName. You would change this to the class it is currently located within. The full class name is included because it’s inside a nested statement, therefore fully qualified names are required.
timePicker = new TimePickerDialog(MyClassName.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// the onTimeSet method will get the hour and minute AFTER the user clicks the set button on the TimePickerDialog
//To test, add a toast, using a
//context of: getBaseContext()
//and a message of: ""Hour: " + hourOfDay + " Minute: " + minute
//context of: getBaseContext()
//and a message of: ""Hour: " + hourOfDay + " Minute: " + minute
}
} , 7, 54, true); // <- This will set the default time that will display on the TimePickerDialog when displayed
is24HourView set to false |
Resources:
http://developer.android.com/reference/android/app/TimePickerDialog.html#TimePickerDialog(android.content.Context, android.app.TimePickerDialog.OnTimeSetListener, int, int, boolean)