Create AlertDialog with Custom Layout using XML Layout

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

Sometimes it is necessary to use a custom layout in the application. The situation can be visualized by having a login dialog, where user would be asked for their login username and password. It would be easy to add single component to the AlertDialog; but when it comes to add multiple views nested inside layouts, it becomes laborious. In latter case, it would be easy to create AlertDialog with custom layout using XML layout.

1. AlertDialog to display information

2. To display and get confirmation from user

3. To display a formatted layout with some components like EditText, CheckBox, etc.




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="Password:" />

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

    <CheckBox
        android:id="@+id/cb_show_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Show Password" />

</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 = (EditText) alertLayout.findViewById(R.id.et_username);
        final EditText etPassword = (EditText) alertLayout.findViewById(R.id.et_password);
        final CheckBox cbShowPassword = (CheckBox) alertLayout.findViewById(R.id.cb_show_password);

        cbShowPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

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

        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", new DialogInterface.OnClickListener() {

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

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

            @Override
            public void onClick(DialogInterface dialog, int which) {
                String user = etUsername.getText().toString();
                String pass = etPassword.getText().toString();
                Toast.makeText(getBaseContext(), "Username: " + user + " Password: " + 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