Get date from datepicker using dialogfragment

前端 未结 9 852
庸人自扰
庸人自扰 2020-11-28 03:42

I\'m using the google example to insert a datepicker inside my app using a dialogfragment
http://developer.android.com/guide/topics/ui/controls/pickers.html

But

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 04:19

    Leszek's answer works, but not if the Dialog is started from another Fragment. In that case you need to use setTargetFragment() in the code that creates the dialog and getTargetFragment() in the dialog code.

    In the code that creates the dialog:

    DialogFragment dialogFragment = new YourDialogFragment();
    dialogFragment.setTargetFragment(YourParentFragment.this, 0);
    dialogFragment.show(getFragmentManager(), "mydialog");
    

    In the DialogFragment code:

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener()
        {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
            {
                YourParentFragment parentFragment = (YourParentFragment) getTargetFragment();
                // Manipulate the parent fragment
                // ...
            }
        };
        // Get the initial date
        // ...
        return new DatePickerDialog(getActivity(), listener, year, month, day);
    }
    

提交回复
热议问题