How do I set the default date in a DatePickerDialog in my fragment from the host activity?

…衆ロ難τιáo~ 提交于 2019-12-13 03:38:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!