Create AlertDialog with Custom Layout Programmatically

As we discussed in the previous post about creating custom layout using XML layout. This post is about creating the same layout programatically. We will be creating all the views to be used in the AlertDialog programatically. Creating layout using XML or programatically is basically developers choice of development. And, it is better to know how things are done programatically, as well.

This post is forth 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.customalertdialogsimpleprogrammatically
Minimum SDK Version19
Activity TypeEmpty Activity
Activity NameMainActivity
Layout Nameactivity_main

Create layout for MainActivity

activity_main.xml: In the MainActivity, we will display a button, when clicked it will display an AlertDialog.

<?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">
    <Button
        android:id="@+id/btn_show_dialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Dialog"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Update MainActivity to Create and Display Custom AlertDialog Programmatically

MainActivity.java: In MainActivity, we will be creating an AlertDialog with one TextView and one EditText in it. These views will be added inside a LinearLayout. All three views will be created programmatically.

package com.pcsalt.example.customalertdialogsimpleprogrammatically;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.util.TypedValue;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
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 -> createAndDisplayDialog());
    }
    private void createAndDisplayDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LinearLayout layout       = new LinearLayout(this);
        TextView tvMessage        = new TextView(this);
        final EditText etInput    = new EditText(this);
        tvMessage.setText("Enter name:");
        tvMessage.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
        etInput.setSingleLine();
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.addView(tvMessage);
        layout.addView(etInput);
        layout.setPadding(50, 40, 50, 10);
        builder.setView(layout);
        builder.setNegativeButton("Cancel", (dialog, which) -> {
            Toast.makeText(this, "Cancel clicked", Toast.LENGTH_SHORT).show();
            dialog.cancel();
        });
        builder.setPositiveButton("Done", (dialog, which) -> {
            String name = etInput.getText().toString();
            Toast.makeText(this, "Name entered: " + name, Toast.LENGTH_SHORT).show();
        });
        builder.create().show();
    }
}

Screenshots:

Download Source Code

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