With the fragment use we often need to use dialog with fragment. Here we will see how to use dialog with fragment and How to use Date-Time picker with the fragment.
Note: Check Fragment.
1. Extend DialogFragment:
public class CustomDialogFragment extends DialogFragment{
//Define constants for date-time picker.
public final int DATE_PICKER = 1;
public final int TIME_PICKER = 2;
public final int DIALOG = 3;
}
2. Add constructor with Fragment argument as It will let know over which fragment, the dialog should be shown.
private Fragment mCurrentFragment;
public CustomDialogFragment ( Fragment fragment ) {
mCurrentFragment = fragment;
}
3. Override onCreateDialog:
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle bundle = new Bundle();
bundle = getArguments();
int id = bundle.getInt("dialog_id");
switch (id) {
case DATE_PICKER:
return new DatePickerDialog(getActivity(),
(OnDateSetListener)mCurrentFragment, bundle.getInt("year"),
bundle.getInt("month"), bundle.getInt("day"));
case TIME_PICKER:
return new TimePickerDialog(getActivity(),
(OnTimeSetListener)mCurrentFragment, bundle.getInt("hour"),
bundle.getInt("minute"), false);
}
case DIALOG:
//Define your custom dialog or alert dialog here and return it.
return dialog;
}
Note: Implement OnDateSetListener, OnTimeSetListener on Fragment.
4. Show the dialog:
CustomDialogFragment dialog = new CustomDialogFragment(YourFragment.this);
Bundle bundle = new Bundle();
bundle.putInt("dialog_id", DATE_PICKER);
bundle.putInt("year", mYear);
bundle.putInt("month", mMonth);
bundle.putInt("day", mDay);
dialog.setArguments(bundle);
dialog.show(getFragmentManager(), "dialog");
Note: For detail description follow the link.
Thanks a lot!
ReplyDeleteIt's a simplest fragment dialog example I've ever seen.
This comment has been removed by the author.
ReplyDelete