Now let’s see how to display Time Picker Dialog in Android
Application. We will use TimePicker Dialog class,
we will use 5 argument constructor, listed below:
1.Context ,
it will be application context
2.Callback function,
used when user select date
3. int for Hour,
which will be visible as selected hour in Time Picker Dialog
4.int for Minutes,
which will be visible as selected minutes in Time Picker Dialog
5.boolean value
to set 24 Hour format or not.
activity_main.xml
---------------------
<LinearLayout 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" tools:context=".MainActivity" android:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Choose Time" android:id="@+id/button" android:layout_gravity="center_horizontal" android:layout_marginTop="25dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Time is :" android:id="@+id/textView" android:layout_marginTop="20dp" /> </LinearLayout>
MainActivity.java
----------------------
package com.android.anil.timepickerdialog; import android.app.TimePickerDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.TimePicker; import java.util.Calendar; public class MainActivity extends AppCompatActivity { Button timepbtn; TextView displaytme; Calendar c=Calendar.getInstance(); int chr,cmin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); timepbtn=(Button)findViewById(R.id.button); displaytme=(TextView)findViewById(R.id.textView); timepbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new TimePickerDialog(MainActivity.this,t1,c.get(Calendar.HOUR_OF_DAY),c.get(Calendar.MINUTE),false).show(); } }); } TimePickerDialog.OnTimeSetListener t1=new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { chr=hourOfDay; cmin=minute; displaytme.setText(chr+":"+cmin); } }; }
Output is:
----------------------
No comments:
Post a Comment