Android Simple Dialog Fragment Tutorial

A Dialog Fragment is a fragment that can be use as a fragment and also showing as a dialog in your activity. It will be same as a fragment lifecycle when it create. Therefore, Google have introduce new Dialog Fragment to overcome the disadvantages of using Dialog. Why choose Dialog Fragment over Dialog? DialogFragment has lifecycle management for configuration changes such as screen rotation. It will restore the state if your app process is killed in the background and user returns to it later. If you using Dialog you will need to handle that situation in another way. In this tutorial, I will teach you how to use dialog fragment on your android project.

Creating a New Project

1. Open Android Studio IDE in your computer.
2. Create a new project and Edit the Application name to “DialogFragmentExample”.
(Optional) You can edit the company domain or select the suitable location for current project tutorial. Then click next button to proceed.
3. Select Minimum SDK (API 15:Android 4.0.3 (IceCreamSandwich). I choose the API 15 because many android devices currently are support more than API 15. Click Next button.
4. Choose “Empty Activity” and Click Next button
5. Lastly, press finish button.

Create a custom dialog

Right click your layout folder and create a new xml file “custom_df.xml” for the dialogfragment. After that, copy the source code below to your xml file. This is a sample layout you want to show in this dialog.

Create a new Custom Dialog Fragment class

Right click your package name from your java folder and create a new class “CustomDFragment”. This class will be show the layout of the custom_df.xml and extends the DialogFragment class.

Create another class for AlertDialog

Create another class “AlertDFragment”, This class will recreate dialog to alert dialog. So this alertdialog will have the lifecycle of fragment.

Edit activity_main.xml layout

Modify your activity_main.xml to the following source code, this layout will have two buttons on it.

Edit MainActivity.java class

Copy and paste the sample below, it will be showing the custom dialog fragment and alert dialog fragment.

Edit styles.xml

Dont forgot to edit styles.xml, you should edit the style of Dialog if your dialog title is not showing in your dialog fragment.

Run Your Project

Lastly, you can try the simple dialog Fragment in your android device. Run it and test it right now.

(Android Simple Dialog Fragment)

Source Code

(Visited 1,205 times, 1 visits today)
Advertisements

Kristofer Ng

A crazy android and web developer. Passion on developing android application and exploring new technology as a hobby.

You may also like...

Leave a Reply

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

GET YOUR EBOOK FOR FREE

Unlock free ebook "Beginning Programming ALL-IN-ONE Desk Reference for DUMMIES" now!

We will send a copy to your email