Sunday, 14 August 2016

How To Make Alert Dialog Box In Android Studio ?



In this tutorial you will learn how to make a alert dialog box in android. here, we will open this alert dialog when a button is clicked or back button is pressed. As you see in snapshot it is asking for confirmation "Yes" or "No", So i have also added a toast when the button is clicked.

So, lets start with creating a new project : 

Step 1 : Open your activity_main.xml  and add  a button as given below in the code: 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    android:background="#42a5f5"
    tools:context="github.deepak.alertdialog.MainActivity">

    <Button        
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Click me to show alert dialog "
        android:id="@+id/btn"
        android:layout_gravity="center"/>
</LinearLayout>
 
Step 2 : Now open the MainActivity.java and add the following to code, don't worry i will explain you after  this for now just add the code.


Now, lets see what is happening in code we have first added the reference of button to java class and set a listener on button. Then a using AlertDialog.Builder library we are showing a alert dialog box. On clicking on button "yes" or "no" ,I have also added Toast Message for better understanding.
If You want to show this alert dialog box when you press back button then change the code as given below:
   

You can download the source code of above application from the link geiven below.
Download the source code here. 

No comments:

Post a Comment