Very simple example of using Alert Dialog in Material design in Android which is very handy for using in confirmations or simple information thats needs to be acknowledged. First of all, this thing comes with adding an implementation in build.gradle file, if you dont have it already because it is common thing to have in your project.

After this, we can use our AlertDialog with Builder.

As you can see we use JAVA 8 for this example, using Lambda expressions like ()-> and you can find tutorials here.
Add this lines inside

In this case we have a method called exit confirmation dialog for displaying the content. Every time the user wants to exit the app, this dialog will pop up:


As you can see it is quite simple and straight forward. Builder helps us to build the dialog before showing it on the display. In our case we use only .setMessage() and .setPositiveButton() with .setNegativeButton() with listeners when they are clicked. There is other methods to build the AlertDialog, like .setTitle(), setNeutralButton() and others helping to modify the dialog as you want. On OK (positive button) click, we finish the activity/exit the app, but you can do what ever you want. Outside or on CANCEL (negative button) we dismiss the dialog and it is not shown on the display anymore.

The color for the text in the buttons is drawn from color resources. accent color, so you can change there or make style for the dialog in style resources.

You can get the whole project on GitHub BuktopMKD/MaterialDesign-AlertDialog

 

Spread the love

Leave a Reply

Your email address will not be published.