Android Adventures - Dialog Classes In DialogFragments
Written by Mike James   
Thursday, 31 July 2014
Article Index
Android Adventures - Dialog Classes In DialogFragments
Communicating with the Activity
Date and Time Picker Dialogs

Custom AlertDialog

What if you want to add some custom UI to the AlertDialog? 

One answer might be that you would probably be better off not using the AlertDialog in this case as the DialogFragment is up to the job and simpler. 

However there are advantages to adding custom UI to the AlertDialog and it isn't difficult. 

Let's display the DialogFragment's layout in the AlertDialog. To do this we need to make the addition to the Builder before the create method is called. 

To use the layout file we need to first inflate it into a hierarchy of View objects and to do this we need a LayoutInflater:

public Dialog onCreateDialog(
              Bundle savedInstanceState) {
LayoutInflater inflater
             =getActivity().getLayoutInflater();

Next we inflate the layout file to get the View hierarchy:

View v=inflater.inflate(
          R.layout.fragment_my_dialog, null);

Finally we use the Builder's setView method to set the view. This can go anywhere but it has to go before the .create method:

 .setView(v)
 .create();
 return myAlert;
}

Now if you run the app you will see the generated layout saying "Hello blank Fragment" in the display area of the dialog. 

You can of course customize the layout file using the designer to be anything you want.

If you want to add customization in code to the layout, e.g. add a button click event handler, then you can do it in the usual way and you can do this before or after the dialog has been created.

For example, if you add a Button to the layout you can add an event handler using:

 .create();
 Button myButton=
           (Button) v.findViewById(R.id.button);
 myButton.setOnClickListener(
             new View.OnClickListener() {
   @Override
   public void onClick(View v) {
}
  });

The only difficult part is remembering to use the View hiearchy to find the Button.

Advantages And Disadvantages

If you use an AlertDialog box to generate the UI of the DialogFragment then you cannot use it as part of the Activity's UI i.e. without a separate dialog window.

A DialogFragment based on an AlertDialog can only be displayed as a dialog. 

However, if you use the DialogFragment approach then it can be managed by the FragmentManager and it can be added to the backstack in the usual way. In addition you can create dialogs that you can use with any Activity, i.e. they are truly reusable.

Date And Time Picker Dialogs

The date and time pickers are available as widgets or as full Dialog classes. We have already looked at how to use them as widgets in chapter six and seven along with the number picker which doesn't have an alternative Dialog class but which can be packaged into one if you really need to.

As with any dialogs you can use the date and time picker dialogs standalone but it is much better to package them into DialogFragments. How you do this is exactly the same as for any other dialog but it is worth a quick look.

For example to create a date picker dialog as a DialogFragment you simply have to return a DatePickerDialog in the onCreateDialog:

public Dialog onCreateDialog(
                  Bundle savedInstanceState) {
DatePickerDialog datePick=
   new DatePickerDialog(getActivity(),
    new DatePickerDialog.OnDateSetListener() {
     @Override
     public void onDateSet(DatePicker view,
      int year, int monthOfYear, int dayOfMonth) {
}
    },
   2014,6,30 );
 return datePick;
}

The last three parameters of the constructor set the initial date. There is a method that lets you get the DatePicker widget in the dialog so you can work with it directly. The callback provides the date the user selected and this should be routed to the Activity if necessary via the usual Fragment Interface pattern.

 

datepick

 

The TimePickerDialog works in the same way 

@Override
public Dialog onCreateDialog(
                     Bundle savedInstanceState) {
 
 TimePickerDialog timePick=
   new TimePickerDialog(getActivity(),
    new TimePickerDialog.OnTimeSetListener() {
     @Override
     public void onTimeSet(TimePicker view,
                    int hourOfDay, int minute) {
}
     },
   23,10,true);
 return timePick;
}

The final three parameters in the constructor give the hours and minutes and whether to use the 24 hour clock or not. 

 

timepick

 

What about the number picker as a dialog?

You could use it to customize an AlertDialog via a layout but it makes much more sense to simply display it using a DialogFragment. Using this approach it gets all the advantages of a Fragment and it can be shown as a dialog or embedded in the UI as required.  The biggest problem is that number pickers are usually used in combination - to enter a multi-digit number say. So to create a good number picker dialog box you would need to allow for different numbers of number pickers. Very do-able but difficult to do well.

Summary

  • There are two ways of creating a DialogFragment's UI - via the onCreateView and by customizing the onCreateDialog to return a dialog complete with UI.

  • To create and AlertDialog you use a builder to add the controls and text that make up the UI. 

  • When the AltertDialog is fully specified the builder's create method is called to actually create it. 

  • You use the DialogFragment in exactly the same way no matter how the dialog UI has been created. You call the DialogFragment's show method to add it to the FragmentManager.

  • Never call the dialog's show method as this just shows the dialog and cuts out any involvement the DialogFragment has in the process. 

  • You can handle events within the DialogFragment in the usual way, but you need to use the Fragment Interface pattern to allow the Activity to handle any dialog events.

  • As well as AlertDialog there are also two useful dialogs - the datepicker and timepicker dialog - there is no number picker dialog.

You can download the code for the programs from the CodeBin (note you have to register first).

 

Android Adventures - Mastering Fragments & Dialogs

coverfrag

Contents

This book is currently being revised. Chapter 5 and later refer to an earlier version of Android Studio - revisit for updates.

  1. Introducing Fragments
  2. Fragments and Android Studio XML
  3. Static Fragments
  4. Dynamic Fragments (Coming soon)

  5. Fragment And Activity Working Together
  6. Managing Fragments
  7. Custom dialogs using DialogFragment
  8. Dialog Classes In DialogFragment
  9. A NumberPicker DialogFragment Project
  10. ViewPager

If you are interested in creating custom template also see:

Custom Projects In Android Studio

Androidgears

To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter,FacebookGoogle+ or Linkedin,  or sign up for our weekly newsletter.

appC

 



 

Comments




or email your comment to: comments@i-programmer.info



Last Updated ( Saturday, 25 July 2015 )