使用建议日期打开DatePicker

时间:2017-02-07 21:44:55

标签: java android android-datepicker

我需要根据GregorianCalendar的YEAR-MONTH-DAY_OF_MONTH属性打开一个默认日期的DatePicker。

以下是我打开DatePicker的代码:

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

例如,如果我的值是这样的:

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

打开DatePicker时设置的默认值为:

enter image description here

我必须添加什么才能做到这一点?

1 个答案:

答案 0 :(得分:3)

基本上直接来自Android | Pickers

另外,就像任何其他片段一样,您可以使用setget - Arguments将数据传递到片段中。

详细信息: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
    }
}

并使用newInstance方法。

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