Create AlertDialog with Custom Layout using XML Layout

Home / Android / Create AlertDialog with Custom Layout using XML Layout

As application grows or while building an application for larger group, sometimes it is necessary to use a custom layout in the AlertDialog. The situation can be visualized by having a login dialog, where user would be asked for their login credentials.

While creating custom layout for AlertDialog, we have two options, if the custom UI is simple enough to display one or two components then this could be done programmatically, else we need to create an XML layout and include that into the AlertDialog.

This post is third in series of tutorials for creating and displaying AlertDialog.

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




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 Custom Alert Dialog
Package Name com.pcsalt.example.customalertdialog
Minimum SDK Version 16
Activity Type Empty Activity
Activity Name MainActivity
Layout Name activity_main

Prepare layout to be displayed in the AlertDialog

We will create something similar to login dialog. It will contain two EditText, two TextView, one CheckBox and one Button.

layout_custom_dialog.xml: This layout will be inflated inside AlertDialog to ask user for Username and Password. And, on click of Login a Toast message will be displayed with username and password.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="15dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".3"
            android:text="Username:" />

        <EditText
            android:id="@+id/et_username"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".7"
            android:imeOptions="actionDone"
            android:singleLine="true" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".3"
            android:text="Email:" />

        <EditText
            android:id="@+id/et_email"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".7"
            android:imeOptions="actionDone"
            android:inputType="textEmailAddress"
            android:singleLine="true" />
    </LinearLayout>

    <CheckBox
        android:id="@+id/cb_show_pass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Toggle Password/Text View" />

</LinearLayout>

Create layout for MainActivity

activity_main.xml: In the MainActivity, we will display a button which will display an AlertDialog.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:onClick="buttonClicked"
        android:text="Hello World!" />
</RelativeLayout>

Update MainActivity to display AlertDialog with custom layout using XML

MainActivity.java: In MainActivity, we will implement following behaviors:
– Click on Button will display an Alertdialog
AlertDialog will use the XML layout to display UI components
CheckBox will toggle the password view
– Click on Login will display a Toast message with username and password.

package com.pcsalt.example.customalertdialog;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
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 buttonClicked(View view) {
        LayoutInflater inflater = getLayoutInflater();
        View alertLayout = inflater.inflate(R.layout.layout_custom_dialog, null);
        final EditText etUsername = alertLayout.findViewById(R.id.et_username);
        final EditText etEmail = alertLayout.findViewById(R.id.et_email);
        final CheckBox cbToggle = alertLayout.findViewById(R.id.cb_show_pass);

        cbToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // to encode password in dots
                    etEmail.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {
                    // to display the password in normal text
                    etEmail.setTransformationMethod(null);
                }
            }
        });

        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("Info");
        // this is set the view from XML inside AlertDialog
        alert.setView(alertLayout);
        // disallow cancel of AlertDialog on click of back button and outside touch
        alert.setCancelable(false);
        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getBaseContext(), "Cancel clicked", Toast.LENGTH_SHORT).show();
            }
        });

        alert.setPositiveButton("Done", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                String user = etUsername.getText().toString();
                String pass = etEmail.getText().toString();
                Toast.makeText(getBaseContext(), "Username: " + user + " Email: " + pass, Toast.LENGTH_SHORT).show();
            }
        });
        AlertDialog dialog = alert.create();
        dialog.show();
    }
}

Screenshots:

Create AlertDialog with Custom XML Layout 1 Create AlertDialog with Custom XML Layout 2 Create AlertDialog with Custom XML Layout 3 Create AlertDialog with Custom XML Layout 4 Create AlertDialog with Custom XML Layout 5 Create AlertDialog with Custom XML Layout 6

Download Source Code

Download Source Code