Search code examples
javaandroidandroid-datepicker

Open DatePicker with suggested date


I need to open a DatePicker with a default date based on the YEAR-MONTH-DAY_OF_MONTH properties of a GregorianCalendar.

Here is the code where I open the DatePicker:

DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");

For exemple, if my values are like this:

  • MyCalendar.YEAR = 2017
  • MyCalendar.MONTH = 2
  • MyCalendar.DAY_OF_MONTH = 22

The default value set when I open the DatePicker would be:

enter image description here

What do I have to add to do that?


Solution

  • Basically straight from Android | Pickers

    Plus, just like any other Fragment, you can use set and get-Arguments to pass data into the fragment.

    Details: Best practice for instantiating a new Android Fragment

    public static class DatePickerFragment extends DialogFragment
                                implements DatePickerDialog.OnDateSetListener {
    
        public static DatePickerFragment newInstance(int year,int month,int day) {
            Bundle b = new Bundle();
            b.putInt("year", year);
            // put others...
    
            Fragment f = new DatePickerFragment();
            f.setArguments(b);
            return f;
        }
    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
    
            // Use the current date as the default date in the picker
            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);
    
            // Update using the arguments
            Bundle args = getArguments();
            if (args != null) {
                year = args.getInt("year");
                // get others...
            }
    
            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }
    
        public void onDateSet(DatePicker view, int year, int month, int day) {
            // Do something with the date chosen by the user
        }
    }
    

    And use that newInstance method.

    DialogFragment newFragment = DatePickerFragment.newInstance(2017,02,07);
    newFragment.show(getFragmentManager(), "datePicker");