Search code examples
androiddatepickerdialogandroid-datepickerdatepickerdialog

How to open date picker dialog?


How Can I open Date Picker Dialog?

I tried using this code, but this doesn't do anything. I believe it has been deprecated, but I haven't found the solution yet.

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

        }
    });

Solution

  • class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
    
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                final Calendar c = Calendar.getInstance();
                int year = c.get(Calendar.YEAR);
                int month = c.get(Calendar.MONTH);
                int day = c.get(Calendar.DAY_OF_MONTH);
    
                return new DatePickerDialog(getActivity(), this, year, month, day);
            }
    
            public void onDateSet(DatePicker view, int year, int month, int day) {
                // get month, year and day
            }
        }
    

    and call this dialog by using this...

    new DatePickerFragment().show(getFragmentManager(), "datepicker");