AlertDialog with custom view

To create an AlertDialog with a custom view, we first have to create the custom view. Let us create a Custom View custom_dialog.xml containing a TextView, an ImageView and a Button.

<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:orientation="vertical"
	android:background="#FFFFFF"
	android:gravity="center_horizontal">

	<ImageView
		android:src="@drawable/image_run"
		android:layout_width="160dp"
		android:layout_height="160dp"
		android:layout_margin="10dp"
		android:id="@+id/customdialogImageView1"
		android:scaleType="fitCenter"/>

	<TextView
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Congratulations!"
		android:layout_margin="4dp"
		android:padding="8dp"
		android:id="@+id/customdialogTextView1"
		android:textColor="#20C732"
		android:textStyle="bold"
		android:textSize="18sp"/>

	<TextView
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Level completed"
		android:textColor="#171717"
		android:padding="8dp"
		android:layout_margin="4dp"
		android:id="@+id/customdialogTextView2"
		android:textSize="14sp"
		android:textStyle="bold"/>

	<Button
		android:layout_width="160dp"
		android:layout_height="wrap_content"
		android:text="NEXT LEVEL"
		android:layout_margin="10dp"
		android:id="@+id/customdialogButton1"
		android:elevation="8dp"/>

</LinearLayout>

Now in the MainActivity or any other Activity, use following codes to display the custom_dialog.xml in an AlertDialog.

final AlertDialog builder = new AlertDialog.Builder(MainActivity.this).create();
				
				View custom_view = getLayoutInflater().inflate(R.layout.custom_dialog, null);
				Button dialog_button1 = custom_view.findViewById(R.id.customdialogButton1);
				
				dialog_button1.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View _v) {
						builder.dismiss();
					}
				});
				builder.setView(custom_view);
				
				builder.show();

That’s all. Try the code now and check.