Android TimePicker is a facility that allow you to give option to select time in your android application. The time will be consisting of hours,minutes etc.. Android itself is providing a TimePickerDialog class for selecting time. In this tutorial we will see how to implement TimePicker in android.This Android TimePicker example will consist of a TextView and a Button, the onclick of button will open a time picker and the selected time will be displayed in the TextView.
- First step is to add the following code to your layout file, which will create a Textview and a Button
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.example.picker.MainActivity" tools:showIn="@layout/activity_main"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_centerVertical="true"> <TextView android:id="@+id/tv_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" android:layout_gravity="center_horizontal" android:textStyle="bold"/> <Button android:id="@+id/btn_time" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:textColor="@color/white" android:layout_marginTop="5dp" android:text="Set Time"/> </LinearLayout> </RelativeLayout>
2. Now use the following code in the onclick of button in your activity.
// Get Current time final Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { tv_time.setText(hourOfDay + ":" + minute); } }, hour, minute, false); timePickerDialog.show();
Now run the code, here is the expected output.

how to show AM and PM in the text Field
I love it, worked like a charm, in my case I added two of them with the corresponding two buttons and they appear one after another, this is not a problem for me as it’s functional for what I want, but is there any reason it does that? Thanks very much.
Welcome kevin