Friday, 10 February 2012

DatePickerDialog & TimePickerDialog in Android

DatePickerDialog is not a View, that you can’t define it in the xml layout file.
Instead you declare it from code with the following two constructors:




DatePickerDialog(Context context, DatePickerDialog.OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth);
DatePickerDialog(Context context, int theme, DatePickerDialog.OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth);


You can use it like this:
public void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn=(Button)findViewById(R.id.btn);

final OnDateSetListener odsl=new OnDateSetListener()
        {

   public void onDateSet(DatePicker arg0, int year, int month, int dayOfMonth) {
    // TODO Auto-generated method stub
    TextView txt=(TextView)findViewById(R.id.txt);
    txt.setText("The date is "+dayOfMonth+"/"+month+"/"+year);
   }
         
        };

btn.setOnClickListener(new OnClickListener()
        {

   public void onClick(View arg0) {
    // TODO Auto-generated method stub
   
    
    Calendar cal=Calendar.getInstance();
    DatePickerDialog datePickDiag=new DatePickerDialog(DateTimeControls.this,odsl,cal.get(Calendar.YEAR),cal.get(Calendar.MONTH),cal.get(Calendar.DAY_OF_MONTH));
    datePickDiag.show();
   }
         
        }
        
        );

}


To take an action when the date is set you define an OnDateSelectedListner and implement the onDateSet method

TimePickerDialog

DatePickerDialog is similar to DatePickerDialog but used for setting time.

The constructors for TimePickerDialog are:

TimePickerDialog(Context context, TimePickerDialog.OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView);

TimePickerDialog(Context context, int theme, TimePickerDialog.OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView);
Code :  
public void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn=(Button)findViewById(R.id.btn);
}

final OnTimeSetListener otsl=new OnTimeSetListener()
        {

   public void onTimeSet(TimePicker arg0, int hourOfDay, int minute) {
    // TODO Auto-generated method stub
    TextView txt=(TextView)findViewById(R.id.txt);
    txt.setText("The time is "+hourOfDay+":"+minute);
   }
        };

btn.setOnClickListener(new OnClickListener()
        {

   public void onClick(View arg0) {
    // TODO Auto-generated method stub
   
    
    Calendar cal=Calendar.getInstance();
    TimePickerDialog timePickDiag=new TimePickerDialog(DateTimeControls.this,otsl,cal.get(Calendar.HOUR_OF_DAY),cal.get(Calendar.MINUTE),true);
    timePickDiag.show();
   }
         
        }
        
        );

1 comment:

  1. Date Picker in android studio
    http://themasterworld.com/creating-date-picker-in-android/

    ReplyDelete