Wednesday, July 11, 2012

DatePickerDialog in Android



Click Here to Download source code 
 

Package Name    :   selva.datepicker 

Project Name      :   DatePickerDialog

Version               :   1.5 (Supports 1.5 and above versions)

main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ShowDatepickerDialog" />

</LinearLayout>



DatePickerDialogActivity.java



package selva.datepicker;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Toast;
import android.app.DatePickerDialog;
import java.util.Calendar;

public class DatePickerDialogActivity extends Activity
{
    int yr, month, day;
    static final int DATE_DIALOG_ID = 1;
    DatePicker datePicker;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
      
       
        Button btnOpen = (Button) findViewById(R.id.button1);
       
        btnOpen.setOnClickListener(new View.OnClickListener()
        {
        public void onClick(View v)
        {
      
             Calendar today = Calendar.getInstance();
             yr = today.get(Calendar.YEAR);
             month = today.get(Calendar.MONTH);
             day = today.get(Calendar.DAY_OF_MONTH);
             showDialog(DATE_DIALOG_ID);
           
        }
        });
       
    }
   
    @Override
    protected Dialog onCreateDialog(int id)
    {
        switch (id)
        {
  
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this, mDateSetListener, yr, month, day);
        }
    return null;
    }
   
    private DatePickerDialog.OnDateSetListener mDateSetListener =
    new DatePickerDialog.OnDateSetListener()
    {
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
    {
        yr = year;
    month = monthOfYear;
    day = dayOfMonth;
    Toast.makeText(getBaseContext(), "You have selected :" + (month + 1) + "/" + 
              day+ "/" + year,Toast.LENGTH_SHORT).show();
    }
    };
}



OUTPUT: 
























Click ShowDatepickerDialog button 






































select date and click set button 











































 Click Here to Download source code



No comments:

Post a Comment