我需要根据GregorianCalendar的YEAR-MONTH-DAY_OF_MONTH属性打开一个默认日期的DatePicker。
以下是我打开DatePicker的代码:
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
例如,如果我的值是这样的:
打开DatePicker时设置的默认值为:
我必须添加什么才能做到这一点?
答案 0 :(得分:3)
基本上直接来自Android | Pickers
另外,就像任何其他片段一样,您可以使用set
和get
- 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");