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 clicked.
This is the full code from the example project shown in the image above:
MainActivity.java
public class MainActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} public void showAlertDialogButtonClicked(View view) { // create an alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Name"); // set the custom layout
final View customLayout = getLayoutInflater().inflate(R.layout.custom_layout, null);
builder.setView(customLayout); // add a button
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {…