Tuesday 6 March 2012

Fragment Dialog and Date-Time Picker

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.

profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

2 comments:

  1. Thanks a lot!
    It's a simplest fragment dialog example I've ever seen.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete