Create Alert Dialog – Android Studio

In this tutorial we will use alert dialog to alert the user whether you want to perform specific function or not. Alert Dialog will contain icon, title, message and two buttons “Yes”, “No”. We will show a alert dialog on button click

Step 1: Create a new project OR Open your project


Step 2: Code

activity_main.xml:

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/showsnackbarbtn"
        android:text="Show Alert Dialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.java:

package com.jigopost.myapplication;


import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button showDialogBtn;

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

        showDialogBtn = findViewById(R.id.showsnackbarbtn);
        showDialogBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(MainActivity.this);
                mAlertDialog.setIcon(R.drawable.close); //set alertdialog icon
                mAlertDialog.setTitle("Title!"); //set alertdialog title
                mAlertDialog.setMessage("Your message here"); //set alertdialog message
                mAlertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        //perform some tasks here
                        Toast.makeText(MainActivity.this, "Yes", Toast.LENGTH_SHORT).show();
                    }
                });
                mAlertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        //perform som tasks here
                        Toast.makeText(MainActivity.this, "No", Toast.LENGTH_SHORT).show();
                    }
                });
                mAlertDialog.show();

            }
        });

    }

}

Step 3: Output

Alert Dialog android

Leave a Reply