Register Login

TimePicker Example in Android

Updated Dec 10, 2019

How to use Time Picker in Android

Timepicker is used to choose any time when making some activity related to time or Android Application related to time setting or time picking.

Please follow the steps given below in order to use timepicker in Android:

Step 1) So first of all, create a blank project for you and then go to your palette and search for date and time category and in here choose timepicker control and drag and drop into your activity.

Step 2) In this example is we are going to show the time chosen by the timepicker in a toast using a button.Therefore please take a button and change the text of this button as ‘show time’ and you can leave the ID as a default.

Step 3) Now our design is complete so we can go to our mainactivity.java in our java folder and declare the object of timepicker and button.

Step 4) So our objects are created now we are going to create a function and in this function, we are going to write a code so that whenever the button is clicked we want to show the time which is picked by timepicker and also cast our object which we have declared.

Step 5) So we have successfully casted both our objects and now we are going to take this object of the button and we will call setOnClick method in this button and then on inside this setOnClickMethod we are going to write the code to show the time.

Step 6) Now inside our onClick method what we are take a toast to show the time Toast.makeText and first instance let’s take the getBaseContext(). Second is the actual, text in which we want to show the time. So for example, we will take this time_picker.getCurrentHour instance, which will give us the current hour plus of we also want to show the minute so after we will concatenate it with minute so time_picker.getCurrentMinute, and the third argument is the duration so toast. LENGTH_SHORT and then show a message.

Step 7) Now the call the function inside onCreate method or copy the function inside onCreate method and we are ready to run our program.

So now our app is running now. You will see the date time picker and the button and you can choose the time by clicking on this green palette and if you want to change the minutes, you can just click the minutes on green palette. You can also change the time by clicking the arrow and dragging it to the time you want to set.

Complete Code

public class MainActivity extends ActionBarActivity{
	private TimePicker time_picker;
	private Button button_show_time;
}

public void showTime(){
	time_picker = (TimePicker)findViewById(R.id.timePicker);
	button_show_time = (Button)findViewById(R.id.button);
}

button_show_time.setOnClickListener(
	new View.OnClickListener(){
		@Override
		public void onClick(View v){
			Toast.makeText(getBaseContext(),time_picker.getCurrentHour() +" : "+ time_picker.getCurrentMinute()+Toast.LENGTH_SHORT).showTime();
		}
	}
)

Read Next About How to use TimePicker Dialog in Android


×