Create AlertDialog with Custom Layout using XML Layout

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 visualised 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 NameCustom Alert Dialog
Package Namecom.pcsalt.example.customalertdialog
Minimum SDK Version16
Activity TypeEmpty Activity
Activity NameMainActivity
Layout Nameactivity_main

Prepare layout to be displayed in the AlertDialog

We will create a dialog with two input boxes (TextInputEditText) which will demonstrate a login form.

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"?>
<androidx.constraintlayout.widget.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"
    android:padding="15dp">

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/til_username"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:hint="@string/username"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/tiet_username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:singleLine="true" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/til_password"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:hint="@string/password"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/til_username"
        app:passwordToggleEnabled="true">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/tiet_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:singleLine="true" />
    </com.google.android.material.textfield.TextInputLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

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.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.TextInputEditText;

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 TextInputEditText etUsername = alertLayout.findViewById(R.id.tiet_username);
        final TextInputEditText etPassword = alertLayout.findViewById(R.id.tiet_password);

        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("Login");
        // 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", (dialog, which) -> Toast.makeText(getBaseContext(), "Cancel clicked", Toast.LENGTH_SHORT).show());

        alert.setPositiveButton("Done", (dialog, which) -> {
            String user = etUsername.getText().toString();
            String pass = etPassword.getText().toString();
            Toast.makeText(getBaseContext(), "Username: " + user + " Password: " + pass, Toast.LENGTH_LONG).show();
        });
        AlertDialog dialog = alert.create();
        dialog.show();
    }
}

Screenshots:

Download Source Code

The complete source code is pushed to GitHub repo. Browse it by clicking on the octocat icon.

Browse source code on GitHub