Wednesday, 21 January 2015

TimePickerDialog Example


ScreenShots:






strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Time Picker Dialog</string>
    <string name="button_name">Pick Time</string>

</resources>

activity_main.xml
<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"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button_pickdate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="@string/button_name" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button_pickdate"
        android:layout_marginTop="35dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

MainActivity.java
package com.swamy.timepickerdialog;

import java.util.Calendar;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

public class MainActivity extends Activity {

       Calendar c = Calendar.getInstance();
       TextView display;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);

              Button pickDate = (Button) findViewById(R.id.button_pickdate);
              display = (TextView) findViewById(R.id.textView1);

              pickDate.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           MyTimePicker datePicker = new MyTimePicker();
                           new TimePickerDialog(MainActivity.this, datePicker, c
                                         .get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true).show();
                     }
              });
       }

       class MyTimePicker implements OnTimeSetListener {

              @Override
              public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                     display.setText("Selected Time is :" + hourOfDay + ":"
                                  + minute);
              }
       }

}

No comments:

Post a Comment