To provide a widget for selecting a time, use the Time Picker widget , you to select the time of day in either 24 hour or AM/PM mode. The time consists of hours, minutes and clock format. Android provides this functionality through TimePicker class.
First we have to define the TimePicker component in our activity.xml. It is define as below −
1 2 3 4 |
<TimePicker android:id="@+id/timePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" /> |
After that you have to create an object of TimePicker class and get a reference of the above defined xml component.
1 2 3 |
import android.widget.TimePicker; private TimePicker timePicker1; timePicker = (TimePicker) findViewById(R.id.timePicker); |
In order to get the time selected by the user on the screen, you will use getCurrentHour() and getCurrentMinute() method of the TimePicker Class. Now insert the following code in the onCreate () method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); timePicker = (TimePicker) findViewById(R.id.timePicker); time = (TextView) findViewById(R.id.textView1); calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); int min = calendar.get(Calendar.MINUTE); showTime(hour, min); } //onclick set time button public void setTime(View view) { int hour = timePicker1.getCurrentHour(); int min = timePicker1.getCurrentMinute(); showTime(hour, min); } // show selected time in text view public void showTime(int hour, int min) { if (hour == 0) { hour += 12; format = "AM"; } else if (hour == 12) { format = "PM"; } else if (hour > 12) { hour -= 12; format = "PM"; } else { format = "AM"; } time.setText(new StringBuilder().append(hour).append(" : ").append(min) .append(" ").append(format)); } |
We can also achieve this functionality by TimePickerDialog, which presents the time picker in a floating dialog box at the press of a button. When the time is set by the user, a TextView will update with the new date.
On click of the button, write the below mentioned code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Calendar mcurrentTime = Calendar.getInstance(); int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY); int minute = mcurrentTime.get(Calendar.MINUTE); TimePickerDialog mTimePicker; mTimePicker = new TimePickerDialog(AddReminder.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) { eReminderTime.setText( selectedHour + ":" + selectedMinute); } }, hour, minute, true);//Yes 24 hour time mTimePicker.setTitle("Select Time"); mTimePicker.show(); } }); |
Thanks for reading.