Search code examples
androiddatepickerandroid-datepicker

Datepicker: How to popup datepicker when click on button and store value in variable


I want to show datepicker popup window. I have found some examples but i am not getting it properly. I have one button and i want that when i click on button the datepicker dialog should popup and after setting the date, the date should be stored in a variable. PLease provide me sample code or good links.


Solution

  • Make this class as the inner class in your activity

    if you wanna set the current date as the date you see when you open your datePicker. You can get it like this

    Calendar c = Calendar.getInstance();
    int startYear = c.get(Calendar.YEAR);
    int startMonth = c.get(Calendar.MONTH);
    int startDay = c.get(Calendar.DAY_OF_MONTH);
    
    class StartDatePicker extends DialogFragment implements DatePickerDialog.OnDateSetListener{
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            // Use the current date as the default date in the picker
            DatePickerDialog dialog = new DatePickerDialog(BookingFormActivity.this, this, startYear, startMonth, startDay);
     return dialog;
    
        }
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub
            // Do something with the date chosen by the user
            startYear = year;
            startMonth = monthOfYear;
            startDay = dayOfMonth;
            updateStartDateDisplay();
    
    
        }
        } 
    

    you can call this dialog by setting this method to onClick

      public void showStartDateDialog(View v){
        DialogFragment dialogFragment = new StartDatePicker();
        dialogFragment.show(getFragmentManager(), "start_date_picker");
        }