是否可以只有一个可用于不同活动的 DatePickerFragment?我的 DatePickerFragment:
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
final Calendar cal = new GregorianCalendar();
int year;
int month;
int day;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
updateDate(year, month, day);
}
public void updateDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
cal.set(year, month, day);
}
}
我在这里发现
return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(), year, month, day);
应该可以在 Activiy 中实现 onDateSet。
public class MyActivity extends FragmentActivity implements DatePickerDialog.OnDateSetListener {
...
public void changeDate(View v) {
log("Changing Date");
DatePickerFragment datePickerFragment = new DatePickerFragment();
datePickerFragment.show(getFragmentManager(), "datePicker");
}
public void onDateSet(DatePicker view, int year, int month, int day) {
log(String.format("Date changed: %d-%d-%d", year, month, day));
}
但是 onDateSet 不会被执行。我的错误是什么?我只想要一个可重用的片段,我可以在不同的活动中使用它,而无需在每个活动中编写相同的代码。