We use AlertDialog class to show popups in Android. But sometimes default AlertDialog’s layout is not enough to fulfill our requirement. So that we have to create Alert Dialog with custom layout. This article explains how to create AlertDialog with Custom XML Layout in Kotlin Android.
Basic Kotlin Code to populate Custom XML Layout in AlertDialog
var dialog: AlertDialog? = null val builder = AlertDialog.Builder(this) // set the custom layout val view = layoutInflater.inflate(R.layout.layout_dialog, null) val tvTitle: TextView = view.findViewById(R.id.tv_title) // Get reference of your XML views builder.setView(view) // create and show the alert dialog dialog = builder.create() dialog.show()
An Example of Custom XML Layout in AlertDialog
In this example, we will create a custom AlertDialog using Kotlin, as shown in the following screenshot.

XML Layout File
layout_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:paddingBottom="10dp">
<TextView
android:id="@+id/tv_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="Dialog Title"
android:textSize="20sp"
android:textStyle="bold"
android:gravity="center"
android:background="#0000ff"
android:textColor="#fff"
android:padding="15dp"/>
<TextView
android:id="@+id/tv_detail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="Detail of dialog"
android:textSize="17sp"
android:textColor="#000"
android:padding="15dp"
android:layout_below="@+id/tv_title"/>
<Button
android:id="@+id/bt_done"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Done"
android:layout_below="@+id/tv_detail"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
Kotlin Code
Following is the Kotlin code to Populate above XML layout in an AlertDialog.
var dialog: AlertDialog? = null val builder = AlertDialog.Builder(this) // set the custom layout val view = layoutInflater.inflate(R.layout.layout_dialog, null) // Get Views references from your layout val tvTitle: TextView = view.findViewById(R.id.tv_title) val tvDetail: TextView = view.findViewById(R.id.tv_detail) val btDone: Button = view.findViewById(R.id.bt_done) tvTitle.setText("Dialog Title") tvDetail.setText("This is title detail") btDone.setOnClickListener(View.OnClickListener { dialog?.dismiss() }) builder.setView(view) // create and show the alert dialog dialog = builder.create() dialog.show()
In the above code, You can see I have got the reference to my XML TextViews and button. You can modify this section of code according to your own custom layout.
That’s it. Enjoy 🙂
For other helping, code snippets have a look at our Kotlin Articles List.