DatePicker Dialog


A Date Picker is a widget that allows the user to select a month, day and year.

Designing Part:


Layout file: Main.xml
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
   
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"/>
   
<TextView android:id="@+id/dateDisplay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""/>

<Button android:id="@+id/pickDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Change the date"/>  
</LinearLayout>


For the layout, we're using a vertical LinearLayout, with a TextView that will display the date and a Button that will initiate the DatePicker dialog. With this layout, the TextView will sit above the Button. The text value in the TextView is set empty, as it will be filled with the current date when our Activity runs.


android:layout_width:Specifies the basic width of the view. This is a required attribute for any view inside of a containing layout manager.

android:layout_height :Specifies the basic height of the view.

android:text.: Provides classes used to render or track text and text spans on the screen.

Coding Part:

package com.Datepicker.project;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class DatePickerActivity extends Activity {
    /** Called when the activity is first created. */
      private TextView mDateDisplay;
      private Button mPickDate;
     
      private int mYear;
      private int mMonth;
      private int mDay;

      static final int DATE_DIALOG_ID = 0;
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
            // capture our View elements
            mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
            mPickDate = (Button) findViewById(R.id.pickDate);
            mPickDate.setOnClickListener(new View.OnClickListener() {
                 
            public void onClick(View v) {
                        showDialog(DATE_DIALOG_ID);
                  }
            });

            // get the current date
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);
            updateDisplay();
      }
     
      @Override
      protected Dialog onCreateDialog(int id) {
            switch (id) {
                  case DATE_DIALOG_ID:
                        return new DatePickerDialog(this,
                                          mDateSetListener,
                                          mYear, mMonth, mDay);
            }
            return null;
      }
     
      private void updateDisplay() {
            mDateDisplay.setText(
                        new StringBuilder()
                        // Month is 0 based so add 1
                        .append(mMonth + 1).append("-")
                        .append(mDay).append("-")
                        .append(mYear).append(" "));
      }
     
      private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {
                  public void onDateSet(DatePicker view, int year,
                              int monthOfYear, int dayOfMonth) {
                              mYear = year;
                              mMonth = monthOfYear;
                              mDay = dayOfMonth;
                              updateDisplay();
                  }
            };
}
Explanation for javaCode:

We start by instantiating variables for our Views and date fields. The ATE_DIALOG_ID is a static integer that uniquely identifies the Dialog. In the onCreate() method, we get prepared by setting the layout and capturing the View elements.


mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
mPickDate = (Button) findViewById(R.id.pickDate);


Then we create an on-click listener for the Button, so that when it is clicked it will show our DatePicker dialog. The showDialog() method will pop-up the date picker dialog by calling the onCreateDialog() callback method.

         
        mPickDate.setOnClickListener(new View.OnClickListener() {
                  public void onClick(View v) {
                        showDialog(DATE_DIALOG_ID);
                  }
            });


We then create an instance of Calendar and get the current year, month and day. Finally, we call updateDisplay() our own method (defined later) that will fill the TextView.


          
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);
           
            updateDisplay();
      }
     


Next, onCreateDialog() callback method. This method is called by showDialog() and it is passed the identifier we gave showDialog() and initializes the DatePicker to the date we retrieved from our Calendar instance.

@Override
   protected Dialog onCreateDialog(int id) {
     
     
switch (id) {
 
     
case DATE_DIALOG_ID:
       return new DatePickerDialog(this,mDateSetListener,
                                          mYear, mMonth, mDay);
            }
            return null;
      }

The updateDisplay() method uses the member date values to write the date to our TextView. 

      // updates the date we display in the TextView
      private void updateDisplay() {
            mDateDisplay.setText(
                        new StringBuilder()
                        // Month is 0 based so add 1
                        .append(mMonth + 1).append("-")
                        .append(mDay).append("-")
                        .append(mYear).append(" "));
      }



 This OnDateSetListener() method listens for when the user is done setting the date (clicks the "Set" button). At that time, this fires and we update our member fields with the new date defined by the user and update our TextView by calling updateDisplay().


      // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {
                 public void onDateSet(DatePicker view, int year,
                              int monthOfYear, int dayOfMonth) {
                              mYear = year;
                              mMonth = monthOfYear;
                              mDay = dayOfMonth;
                              updateDisplay();
                  }
            };
}

Comments

  1. if i want to set minimum date then how can i set in datepicker.......pls reply my mail arunkumar.k@npcompete.net

    ReplyDelete

Post a Comment

Popular posts from this blog

How To Run Compatibility Test Suite (CTS) ?

NFC : Reading a MiFare Classic 1K from Android Devices

Dalvik Virtual machine VS Java Virtual Machine: