【发布时间】:2015-12-19 01:26:31
【问题描述】:
DatePickerDialog 被加载到 Fragment 中,当对话框首次打开时,今天的显示是默认日期。然后用户选择一个日期,然后关闭对话框。下次重新打开时,如何将之前选择的日期显示为默认日期,而不是显示今天的日期?
我在 Activity 中尝试过 .set() 但不知道如何使用 .get() 来检索片段中的日期。我已经尝试在 Activity 和 Fragment 之间使用侦听器的接口,但无法使其正常工作,而且对于我试图实现的简单任务来说似乎过于复杂。我已经尝试过从 Activity 发送到片段的捆绑包,但我也无法让它工作。请指教。
活动文件:
...
final Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
片段文件:
...
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);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Save selected date in a date variable here? How?
// How do I then use the date variable in onCreateDialog
// rather than the get(Calendar) code that returns today's date?
}
}
【问题讨论】:
-
将其保存到一个变量中,并在再次打开对话框时将选择器设置为您的日期变量。
-
您应该将值保存在 SharedPreferences 中。这是在应用程序的多次打开和关闭之间保存隔离值的适当 Android api。
-
@sean 该线程的哪一部分?我设置了一个监听器,但它不起作用,而且看起来过于复杂。
-
@David 首先,我需要将今天的日期显示为默认日期......我可以轻松做到(参见上面的片段代码)。在下一次打开时,我需要使用之前选择的日期设置选择器。你能提供一个我可以尝试的例子吗?
标签: android date android-fragments