Monday, 17 October 2016

TimePicker

TimePicker is android widget. And it allows to select the time by hour, minute. But we can't select the second only. It is nothing but FrameLayout class (i.e its subclass).So please follow example timepicker code below detail.

activitymain.xml :-

<?xml version="1.0" encoding="utf-8"?>
<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" 
 android:orientation="vertical"  
 tools:context="com.kiranapp.MainActivity">
<TextView 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:text="time :" 
 android:id="@+id/textView"  
 android:layout_marginTop="20dp" 
 android:layout_alignParentTop="true"  
 android:layout_centerHorizontal="true" 
 android:layout_gravity="center_horizontal" />
<Button 
 android:layout_width="wrap_content"  
 android:layout_height="wrap_content" 
 android:text="Select time"  
 android:id="@+id/button" 
 android:layout_marginTop="10dp" 
 android:layout_below="@+id/textView" 
 android:layout_centerHorizontal="true" 
 android:layout_gravity="center_horizontal" />
</LinearLayout>

MainActivity.java :-

package com.kiranapp;

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 selectbtn;
    TextView displaytime;
    Calendar c=Calendar.getInstance();
    int chr,cmin;

@Override protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 selectbtn=(Button)findViewById(R.id.button);
 displaytime=(TextView)findViewById(R.id.textView);
 selectbtn.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;
 displaytime.setText("Time is : "+chr+":"+cmin);
 }
};
}

Output :-

TimePicker
TimePicker fig :1





















TimePicker
TimePicker fig:2





















TimePicker
TimePicker fig :3





No comments:

Post a Comment