Create AlertDialog with custom layout programmatically

Home / Android / Create AlertDialog with custom layout programmatically

In this tutorial we are going to create a custom AlertDialog. It will contain a TextView, and an EditText. First of all, create aAndroid Application Project (or you can download the source code).

The activity_custom_alert_dialog.xml goes like



    




As per our application this is the package name.

package com.pcsalt.customalertdialogdemo;

These imports will be needed in the program.

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

This is the Activity class. In which the showAlert() function creates the custom alert dialog.

public class CustomAlertDialogActivity extends Activity {

	Button btnShow;

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

		btnShow = (Button) findViewById(R.id.btnShow);
		btnShow.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showAlert();
			}
		});
	}

	private void showAlert() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		LinearLayout layout       = new LinearLayout(this);
		TextView tvMessage        = new TextView(this);
		final EditText etInput    = new EditText(this);

		tvMessage.setText("Enter name:");
		etInput.setSingleLine();
		layout.setOrientation(LinearLayout.VERTICAL);
		layout.addView(tvMessage);
		layout.addView(etInput);
		alert.setTitle("Custom alert demo");
		alert.setView(layout);

		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});

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

			@Override
			public void onClick(DialogInterface dialog, int which) {
				String name = etInput.getText().toString();
				Toast.makeText(getBaseContext(), name, Toast.LENGTH_SHORT).show();
			}
		});

		alert.show();
	}
}

The final result is:

Download source code: [download id=”5″].