Online Tutorials & Training Materials | STechies.com
Register Login

Alert Dialog Example in Android

|| 0

Alert Dialog Example in Android
Stechies

This tutorial explains step by step how to show or display Alert Dialog in Android Applications via Android Studio.

What is the Alert Dialog?

Alert Dialog box is a popup which occurs  when something unexpected occurred that requires immediate user action. For example, when you press the Back button inside any application to exit, it will show you the Alert dialog which says: for ex Are you sure want to do this? or Do you want to stay in the app? etc.

Please follow the steps below in order to show Alert Dialog in Android:

1.Open Android studio.

2.Go to MainActivity.java.

3.Remove the AppCompat from the Activity.

4.Press Alt + Enter and import it.

5.Add an override method. Type public void onBackPressed()

6.Add final AlertDialog.Builder builder = new AlertDialog.Builder (MainActivity.this). [The activity name in this case is MainActivity]

7.Type the builder message.

8.Press Alt + Enter and Implement the method.

9.You have to cancel the dialog. So put the code dialogInterface.cancel()

10.Add a positive button. When you add the Alert Dialog in the back button, it will automatically close the application.

11.Press Alt + Enter to implement the method.

12. Put finish for exiting the app. Adding finish always means exiting the app.

13.Create the Alert dialog.

14.Finally, you have to show the Alert.

15.Run and check it on your Android device.