Android Example to Create TimePicker View using a Dialog

activity_main.xml

Drag the TimePicker from the pallete.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TimePicker
        android:id="@+id/timePicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="16dp" />

</RelativeLayout>

mainActivity.java

package com.example.scanfcode;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;




public class MainActivity extends Activity 
{
	 TimePicker p1;
	  int h1,m1;

	  static final int t1=0;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		p1=(TimePicker)findViewById(R.id.timePicker1);
		p1.setIs24HourView(true);
		showDialog(t1);
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		switch(id)
		{
		case t1:
			return new TimePickerDialog(
					this,mTimeSetListener,h1,m1,false);
		}
		return null;
	}
	
	private TimePickerDialog.OnTimeSetListener mTimeSetListener= new TimePickerDialog.OnTimeSetListener()
	{
		public void onTimeSet(TimePicker v1, int ho1,int  mi1)
		{
			h1=ho1;
			m1=mi1;
			
			SimpleDateFormat ti1=new SimpleDateFormat("hh:mm::aa");
			Date d1=new Date(0,0,0, h1,m1);
			String s1=ti1.format(d1);
			Toast.makeText(getApplicationContext(),s1,Toast.LENGTH_SHORT).show();
			
		}
	};
	
	public void onClick(View v)
	{
		Toast.makeText(getApplicationContext(),p1.getCurrentHour()+":"+p1.getCurrentMinute(),Toast.LENGTH_SHORT).show();
	}

}

OUTPUT:-

timePicker

Leave a Reply

Your email address will not be published. Required fields are marked *