Android tutorial Custom Alert Dialog using DialogFragment

Why you need a Custom Alert Dialog?

More often, we need a dialog which requires a different functionality as compared to default functions provided by system dialog box. For instance, how would you show Rating Bar in the Alert Dialog? One dirty way to do this is to create a layout file and inflate it in dialog view, which obviously results in low-quality code that is hard to maintain and extend, another way is by setting Dialog theme to Activity. The disadvantage of this approach is that activity often occupies a large block of memory and is comparatively slower than Fragment.

In this tutorial, you will learn how to create a custom Alert Dialog using DialogFragment.

Creating a project

Create a new android studio project, create a default activity.

Working with an example

Abstract: In this tutorial, we will show a RatingBar in a dialog fragment.

Go to app>res, then right click on layout and click New>Layout resource file. Enter file name as fragment_rating. Add the following code to fragment_rating.xml.

  • Go to app>java, right click on your package name and then go to New>Java Class. Enter RatingBarFragment as the¬†class name. Enter Ok.
    Add the following code to your
  • Open, add the following code.

Note: You can remove the dialog title using the following code.

  • Output

    Custom Alert Dialog Android
    Custom Alert Dialog Android

Download the source code

Leave a Reply

Your email address will not be published. Required fields are marked *