You can create TimePicker View using <TimePicker> xml element like this -
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
The TimePicker view displays a standard UI to enable user to set a time. By default, it displays time in the AM/PM format. If you want to change time in the 24 hour format, then you can use the setIs24HourView() method. There are two other important methods of TimePicker -
- getCurrentHour()
- getCurrentMinute()
Please note that getCurrentHour() method always returns the hour in 24-hour format i.e. value from 0 to 23.
activity_main.xml
(res/layout/activity_main.xml)<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display Time" />
</LinearLayout>
TimePickerDemoActivity
(File: TimePickerDemoActivity.java)
package com.example.timepickerdemosimple;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
TimePicker timepicker;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timepicker = (TimePicker) findViewById(R.id.timePicker);
timepicker.setIs24HourView(true);
// Button View
Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
// @Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),"Time Selected : "+timepicker.getCurrentHour()+":"
+timepicker.getCurrentMinute(), Toast.LENGTH_SHORT).show();
}
});
}
Output