Alertdialog in Android

Share this

In many Android app you must have seen alert dialog (message box) with ok button and cancel button.

In this post we will see how to interact with user with the help of alert dialog.

Alert dialog are used to show information message to user.

alert dialog may have button one two or may be three.

lets get started .

1. open android studio

2. create a new project

3. Set application name Alert Dialog

4. I used package path as com.androidcodr.alertdialog click next.

5. On this screen set minimum sdk API 16 click next.

6. Add empty activity. click next.

7. keep Activity name as MainActivity click finish.

wait till project load completely.

8. Goto activity_main.xml

9. if you are having constrainLayout change it to RelativeLayout

10 add a button at center of screen.

set its properties as follows.
text=Show diaolog
padding=20dp
textSize=16sp
onClick=opendialog
layout_margin=20dp
id=@+id/mainbtnsho

 

android alert dialog example with code
android alert dialog

 

<Button
        android:id="@+id/mainbtnsho"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_margin="20dp"
        android:onClick="opendialog"
        android:padding="20dp"
        android:text="Show diaolog"
        android:textSize="16sp" />

11. we already have hello world textview.

change its property as follows

text = Alert dialog example.
textsize = 24sp
gravity= center horizontal
Layout_above=@+id/mainbtnsho

android alert dialog example with code
android alert dialog

 

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/mainbtnsho"
        android:gravity="center_horizontal"
        android:text="Alert dialog example"
        android:textSize="24sp"
        android:textStyle="bold" />

12. now goto MainActivity.java

add method opendialog which we set onClick for button.

 

 public void opendialog(View view){
     
    }

13.Before showing Alert dialog
we have to build it with AlertDialog.Builder
from android.app.AlertDialog system package.

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

 

pass MainActivity.this as context.

14. add title and message for dialog

call setTitle method.

 

builder.setTitle("Android Codr");

for message call setMessage method.

 

builder.setMessage("Have you subscribed us?");

15. you can set cancellable to true or false.

 

builder.setCancelable(false);

if set to true then if user click on screen, outside area of dialog it get dissmissed

16. we will add two button to it.
one button is called PositiveButton
other is called NegativeButton

call setPositiveButton method.

pass first parameter string titles as “YES”
second parameter we have to implement OnClickListener

use autocomplete with ctrl+space.

 

android alert dialog example with code
android alert dialog

 

builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

17. We will show Toast message to user if he press Yes button.

 

Toast.makeText(MainActivity.this, "Thank you for subscribing us!", Toast.LENGTH_SHORT).show();

18. same way add Negative button

 

 builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              
            }
        });

19. We will show Toast message to user if he press NO button.

 

 Toast.makeText(MainActivity.this, "Please subscribe us!", Toast.LENGTH_SHORT).show();

20. finally create dialog from builder

 

AlertDialog alert = builder.create();

21. call show method.

alert.show();

22. run the app.

android alert dialog example with code
android alert dialog

click on show dialog button.
our alert dialog is displayed now.

click on yes button
toast message is displayed.

android alert dialog example with code
android alert dialog

click on no button another toast message is displayed.

android alert dialog example with code
android alert dialog

23. if you want third button in dialog then
add neutral button.

        builder.setNeutralButton("Rate us", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Dont forget to rate us on play store.", Toast.LENGTH_SHORT).show();
            }
        });
android alert dialog example with code
android alert dialog on Kitkat

Here is full code of activity_main.xml

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidcodr.alertdialog.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/mainbtnsho"
        android:gravity="center_horizontal"
        android:text="Alert dialog example"
        android:textSize="24sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/mainbtnsho"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_margin="20dp"
        android:onClick="opendialog"
        android:padding="20dp"
        android:text="Show diaolog"
        android:textSize="16sp" />

</RelativeLayout>

Here is full code of MainActivity.java

package com.androidcodr.alertdialog;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void opendialog(View view){
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Android Codr");
        builder.setMessage("Have you subscribed us?");
        builder.setCancelable(false);
        builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Thank you for subscribing us!", Toast.LENGTH_SHORT).show();

            }
        });

        builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Please subscribe us!", Toast.LENGTH_SHORT).show();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }
}

 

Thank you.
If you Like post. Share with your Friends.
Subscribe us.
Follow us on Facebook Twitter and Google+

 


Share this

Leave a Reply

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