Android的DialogFragment - 获取参考日期选择器 [英] Android DialogFragment - Get reference to date picker
问题描述
Android的文档告诉我们实现像这样日期选择器,延长DialogFragment:
The Android docs tell us to implement date pickers like so, extending DialogFragment:
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@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);
// 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 then to display the date picker dialog in our Activity, we call this method:
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
我需要知道的是,我如何才能在对话框中使用,这样我可以用的方法,如.setMinDate()和.setMaxDate()的实际日期选取器的参考是什么?有什么建议?
What I need to know is, how do I get a reference to the actual date picker used in the dialog so that I may use methods such as .setMinDate() and .setMaxDate()? Any suggestions?
推荐答案
我整理了这一点,与此<一个帮助href=\"http://stackoverflow.com/questions/8456143/dialogfragment-getdialog-returns-null\">StackOverflow回答:
I sorted this out with the help of this StackOverflow answer:
public void showDatePickerDialog() {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
getFragmentManager().executePendingTransactions(); // commits the show method from above
DatePickerDialog dialog = (DatePickerDialog) newFragment.getDialog();
DatePicker datePicker = (DatePicker) dialog.getDatePicker();
Date now = new Date();
datePicker.setMaxDate(now.getTime());
}
您需要调用 .executePendingTransactions()
的片段管理器停止被异步添加对话框片段,否则 getDialog()
方法给出了一个空指针异常。
You need to call .executePendingTransactions()
on the fragment manager to stop the dialog fragment being added asynchronously, otherwise the getDialog()
method gives a null pointer exception.
我把它放在这里,将来任何人谁可能有这个问题。
I am putting it in here for anyone in the future who may have this problem.
这篇关于Android的DialogFragment - 获取参考日期选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!