Create AlertDialog and Basic Usage – Android

Home / Android / Create AlertDialog and Basic Usage – Android

Creating and displaying an AlertDialog depends on the use-case of the application. But, the way of creating and displaying depends on the situation. There are several ways of creating it, so, this post is the first in the series of tutorials to create and display an AlertDialog.

In this series of tutorials, we will be learning from the basics of creating AlertDialog to add customization to it. Whether it is displaying custom view(s) on the dialog or handling the UI interaction of the dialog. All the source code will be available on GitHub and the link will be shared after completion of each post.

Series Index of AlertDialog

  1. Create AlertDialog and Basic Usage
  2. Provide Selection from a list of options
  3. Create AlertDialog with Custom Layout using XML Layout
  4. Create AlertDialog with custom layout programmatically
  5. Create AlertDialog with complex custom layout programmatically
  6. Override Button of AlertDialog

In this post, we will learn to create and use AlertDialog and try to implement all possible ways of using (not custom) AlertDialog.

Create Android Application Project

If you are new to Android Studio, then you could learn about creating new projects from our tutorial Create Android Application Project in Android Studio Continued.

Create Android application project with following attributes.

Project Name AlertDialog Demo
Package Name com.pcsalt.example.alertdialogdemo
Minimum SDK Version 21
Activity Type Empty Activity
Activity Name MainActivity
Layout Name activity_main

Prepare layout to be displayed in the AlertDialog

We will have a Button in the Activity, and clicking on it will display the dialog. For this following is the code for layout.

main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_show_dialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Display Dialog"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>




Update MainActivity to display AlertDialog

We will be displaying all (non-custom) variants of AlertDialog in this application. For this add click listener to the button and display the dialog.

MainActivity.java

package com.pcsalt.example.alertdialogdemo;

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

        findViewById(R.id.btn_show_dialog).setOnClickListener(view -> showDialog());
    }

    private void showDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle("Info");
        dialogBuilder.setMessage("Some informative message for the user.");
        dialogBuilder.setPositiveButton("Done", (dialog, which) -> dialog.dismiss());
        dialogBuilder.create().show();
    }
}

In this showDialog(), we are displaying a dialog with title, message and a button. From now on, in this post only showDialog() method will be tweaked to display all types of native dialogs.

display alertdialog alertdialog with message

Understating the buttons of AlertDialog

AlertDialog have option to configure upto three buttons in it. Buttons are named as

  1. Positive Button: This button is displayed on the bottom left (or bottom-end) corner of the dialog. And, considered to have positive user feedback.
  2. Negative Button: This button is displayed before the positive button and, considered to have negative user feedback.
  3. Neutral Button: This button is placed on the bottom right (or bottom-start) corner of the dialog and allows user to provide neutral feedback.

The best example for these buttons could be the AlertDialog asking user to rate something. For this user should have three options, viz. Rate, Leave it, and May be, later.

In an AlertDialog any combination of the above three buttons can be used. For instance, any of the button could be used and others can be left like in the above example, we are using only positive button.

Now we will create the Rating dialog with the buttons.

private void rateDialog() {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    dialogBuilder.setTitle("Rate Us");
    dialogBuilder.setMessage("If you liked it, please rate it." +
            " If you do not like it rate it." +
            " It will help us grow.");
    dialogBuilder.setPositiveButton("Rate", (dialog, which) -> {
        // take user to the page to rate
        // and dismiss the dialog
        dialog.dismiss();
    });

    dialogBuilder.setNegativeButton("Leave it", (dialog, which) -> {
        // set a flag in system, that user do not want to rate
        // and dismiss the dialog
        dialog.dismiss();
    });

    dialogBuilder.setNeutralButton("May be, later", (dialog, which) -> dialog.dismiss());

    dialogBuilder.create().show();

}

display rate us AlertDialog

Further customizations could be added to this AlertDialog. For instance, add icon to the title of the dialog. Or provide a complete custom layout to the dialog, or leave the title and display dialog with message and a button only. It all depends on how it needs to be displayed.

private void displayDialogWithIcon() {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    dialogBuilder.setTitle("Info");
    dialogBuilder.setIcon(R.mipmap.ic_launcher_round);
    dialogBuilder.setMessage("You know, you could have provided some valuable message here!");
    dialogBuilder.setPositiveButton("Got it", (dialog, which) -> dialog.dismiss());
    dialogBuilder.create().show();
}

display AlertDialog with icon

Download Source Code

Download Source Code

  • krishna dhas

    Hi.. i develop one app. that app i used baseadapter. it’s working eclipse. then i create new project android studio but the android studio project using base adapter getView function not called or run .


    public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    Log.e("getView",""+"getView");
    if (convertView == null) {
    convertView = inflater.inflate(R.layout.chat_listview_layout_screen , parent, false);
    }
    setAttributes(position, convertView);
    convertView.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    click(position);
    }
    });
    return convertView;
    }

    • Hi Krishna,

      Could you please post more of the code (here or GitHub or Gist)? I do not see any problem in this code block, other than final int position. In guidelines, they have said not to make parameters of getView() as final. If you could post the source code of the CustomBaseAdapter you are using, then I could suggest the problem with it.

      You could also refer to ListView using BaseAdapter – Android for more details. This tutorial is created using Android Studio.

      Thank you.

      • krishna dhas

        Really Thanks. It’s too useful for my work………….

        • I am glad, it worked out for you. Happy to help.

          • krishna dhas

            Hi, You have any idea about exact location tracking? now me using one method but that method sometimes get Tower location latitude and longitude other time it works perfectly (GPS Connect time)

          • Hi, if I am right, then you would like to get device location in Android. Sometimes you get tower location but sometimes it provides correct location. And, GPS takes time to connect.

            I would suggest you to try FusedLocationProviderApi. It will provide you the device location (only if location tracking is enabled for the device) with the accuracy level you have set. You can find more here https://developer.android.com/training/location/index.html

          • krishna dhas

            thanks. i have one doubt. if Gps not connected(that means gps on but tower not get properly) that scenario. how to show latitude and longitude?

          • You can display previously cached/stored Latitude and Longitude. And, display a dialog to ask user to turn on the GPS.

  • Pingback: Create AlertDialog with Custom Layout using XML Layout | PCSalt()

  • Pingback: Create AlertDialog 2 – Android | PCSalt()

  • Pingback: Create AlertDialog with Custom Layout Programmatically | PCSalt()