我想从DatePickerDialog迁移到MaterialDatePicker。从MaterialDatePicker调用getDialog时遇到问题,对话框结果始终为空。
这是一个错误,还是MaterialDatePicker不支持该功能?
日期选择器对话框
private static class BirthDateUpdater extends DialogFragment implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// create calendar instance
final Calendar c = Calendar.getInstance();
// set calendar to birthdate
c.setTimeInMillis(getBirthDate().getTime());
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// 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) {
// process date selected in here
}
}
此处的MaterialDatePicker问题-picker.getDialog((的结果始终为空?
public static class BirthDateUpdater extends DialogFragment implements
MaterialPickerOnPositiveButtonClickListener<Long>,
DialogInterface.OnCancelListener {
private Dialog dialog;
public BirthDateUpdater() {
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
try {
// builder
MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();
builder.setTitleText("Select Date");
// set date to BirthDate
builder.setSelection(getBirthDate().getTime());
// picker
MaterialDatePicker<Long> picker = builder.build();
// add event
picker.addOnPositiveButtonClickListener(this);
picker.addOnCancelListener(this);
// dialog
dialog = picker.getDialog(); // error in here (dialog is null)?
} catch (Exception ex) {
ex.printStackTrace();
}
return dialog;
}
@Override
public void onPositiveButtonClick(Long selection) {
try {
Calendar dateSelected = Calendar.getInstance();
dateSelected.setTimeInMillis(selection);
// process date selected in here
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void onCancel(@NonNull DialogInterface dialog) {
dialog.dismiss();
}
}
MaterialDatePicker
已经是DialogFragment。在您的情况下,picker.getDialog()
返回null,因为在引擎盖下,DialogFragment写入值到来自生命周期回调onCreateDialog((的DialogFragment.mDialog(该字段的值返回picker.getDialog()
(,该回调将在调用对话框的show方法后调用async,即,当您调用picker.show(fragmentManager(时,在picker的onCreateDialog中,您可以从getDialog()
方法中获得非空值。
在您的情况下,您不应该扩展DialogFragment或MaterialDatePicker(它是最终的(,而是可以创建类似birthDateUpdater
:的方法
public DialogFragment birthDateUpdater() {
MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();
builder.setTitleText("Select Date");
// set date to BirthDate
builder.setSelection(getBirthDate().getTime());
// picker
MaterialDatePicker<Long> picker = builder.build();
// add event
picker.addOnPositiveButtonClickListener(selection -> {
try {
Calendar dateSelected = Calendar.getInstance();
dateSelected.setTimeInMillis(selection);
// process date selected in here
} catch (Exception ex) {
ex.printStackTrace();
}
});
picker.addOnCancelListener(dialog -> {
dialog.dismiss();
});
return picker
}
或者创建类、工厂,或者任何将封装此逻辑的东西。