Search code examples
javaandroid

How to stack AlertDialog buttons vertically?


I am using builder to create AlertDialogs in Android using the pattern:

AlertDialog.Builder builder = new AlertDialog.Builder(context);

builder.setTitle(...);
builder.setMessage(...);

builder.setPositiveButton(button1Text, ...);
builder.setNeutralButton(button2Text, ...);
builder.setNegativeButton(button3Text, ...);

builder.show();

Currently, only two of the buttons are displayed, because the buttons are too wide to fit in the dialog. How can I enforce the buttons to stack vertically?

I am using the Theme.AppCompat.Dialog.Alert theme, which uses ButtonBarLayout to build the buttons. According to this answer, ButtonBarLayout can stack wide buttons vertically automatically, when its mAllowStacking property is set, but it seems to default to false in my case. Is there a way I can set it to true when I build the AlertDialog?


Solution

  • You can't do that with an AlertDialog . You should create a custom Dialog, and implement that yourself. Something like this would do it

    Dialog dialog = new Dialog(context);
    dialog.setContentView(R.layout.dialog_layout);
    dialog.setTitle(...);
    dialog.setMessage(...);
    dialog.show();
    

    and your layout dialog_layout.xml should be something like

    <LinearLayout android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  orientation="vertical">
    
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    </LinearLayout>