问题
So I created a calendar object "c" in the Activity and set the date to February 29, 2016. I want the fragment dialog to load that date as the default date. What am I missing here? Do I need to delete the fragment calendar object 'cal'? If so, in the fragment onCreateDialog how do I reference or get() the date from the set() method in the Activity?
from Activity file:
@Override
protected void onCreate(Bundle savedInstanceState) {
...
final Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, 2016);
c.set(Calendar.MONTH, 1);
c.set(Calendar.DAY_OF_MONTH, 29);
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
from the Fragment file:
...
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar cal = Calendar.getInstance();
currentyear = cal.get(Calendar.YEAR);
currentmonth = cal.get(Calendar.MONTH);
currentday = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dateDialog = new DatePickerDialog(this.getActivity(), this, currentyear,currentmonth,currentday);
return dateDialog;
回答1:
The Calendar c
you set in your Activity is different from the Calendar cal
in your fragment, they are two different instances.
I suggest you pass the year, month and day to the fragment using a Bundle
, so you would want to go:
Bundle data = new Bundle();
data.putInt("...", "..."); //
DialogFragment df = new DialogFragment();
df.setArguments(data);
Then in your onCreateDialog
in the fragment, retrieve the data using:
int year = getArguments("...");
来源:https://stackoverflow.com/questions/32706796/how-do-i-set-the-default-date-in-a-datepickerdialog-in-my-fragment-from-the-host