This is a repost of an answer I wrote on Stack Overflow.
Sometimes the standard AlertDialogs just don’t meet your needs. It’s not difficult to create a custom alert, though. This post will show you a minimal example. When we’re done, you can follow the same procedure to add any layout you want.
Create a custom layout
A layout with an EditText
is used for this simple example, but you can replace it with anything you like.
custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent"> <EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"/></LinearLayout>
Use the dialog in code
The key parts are
- using
setView
to assign the custom layout to theAlertDialog.Builder
- sending any data back to the activity when a dialog button is…