Thursday, 12 February 2015

How to create a Dialog Fragment in Android ?

* A Dialog Fragment being a fragment, the same rules and regulations apply when constructing a dialog fragment.
* The recommended pattern is to use a factory method such as newInstance() as we did before.
* Inside that newInstance() method, you use the default constructor for your dialog fragment, and then you add an arguments bundle that contains your passed-in parameters.
* You don't want to do other work inside this method because you must make sure that what you do here is the same as what Android does when it restores your dialog fragment from a saved state.
* And all that Android does is call the default constructor and re-create the arguments bundle on it.

Overriding onCreateView :

* When you inherit from a dialog fragment, you need to override one of the two methods to provide the view hierarchy for your dialog.
* The first option is to override onCreateView() and return a view.
* The second option is to override onCreateDialog() and return a dialog.

Overriding onCreateView() of a DialogFragment :

    ........other functions
    public View onCreateView(LayoutInflator inflator, ViewGroup container, Bundle savedInstanceState)
       //Create a view by inflating desired layout
       View v = inflator.inflate(R.layout.prompt_dialog, container, false);
       //you can locate a view and set values
       TextView tv = (TextView)v.findViewById(;
       //you can set callbacks on buttons
       Button dismissBtn = (Button)v.findViewById(;

      Button saveBtn = (Button)v.findViewById(;
      return v;
   .......other functions

Overriding onCreateDialog :

As an alternate to supplying a view in onCreateView(), you can override onCreateDialog() and supply a dialog instance.

Overriding onCreateDialog() of a DialogFragment :

         ...........other functions
      public Dialog onCreateDialog(Bundle icicle)
           AlertDialog.Builder b = new AlertDialog.Builder(getActivity())
             .setTitle("My Dialog Title")
             .setNegativeButton("Cancel", this)
          return b.create();
        ........other functions

* In this example, you use the alert dialog builder to create a dialog object to return.
* This works well for simple dialogs.
* The first option of overriding onCreateView() is equally easy and provides much more flexibility.

No comments:

Post a Comment