96
AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Title");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
            }
        });
        AlertDialog alert = builder.create();

I am using the above code to display an Alert Dialog. By default, it fills the screen in width and wrap_content in height.
How can I control the width and height of default alert dialog ?
I tried:

alert.getWindow().setLayout(100,100); // It didn't work.

How to get the layout params on the alert window and manually set the width and height?

Jonathan Soifer
  • 2,715
  • 6
  • 27
  • 50
sat
  • 40,138
  • 28
  • 93
  • 102

11 Answers11

226

Only a slight change in Sat Code, set the layout after show() method of AlertDialog.

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
builder.setTitle("Title");
alertDialog = builder.create();
alertDialog.show();
alertDialog.getWindow().setLayout(600, 400); //Controlling width and height.

Or you can do it in my way.

alertDialog.show();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();

lp.copyFrom(alertDialog.getWindow().getAttributes());
lp.width = 150;
lp.height = 500;
lp.x=-170;
lp.y=100;
alertDialog.getWindow().setAttributes(lp);
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
PiyushMishra
  • 5,743
  • 6
  • 37
  • 57
  • Can you center the text doing this? – ingh.am Oct 26 '11 at 14:20
  • 1
    @ingo: yes you can, Create an xml belong to Dialog box and in that xml design your text like dialog.setContentView(R.layout.dialog); and in xml you can do anything with the text. – PiyushMishra Nov 09 '11 at 08:20
  • @amit yes you can lp can control anything. – PiyushMishra Oct 23 '12 at 13:41
  • Thanks. The second solution works fine for me, the first one doesn't. Tested with Android API 17. –  Nov 24 '12 at 06:28
  • 4
    @PiyushMishra How to set `height` and `width` which support to all Device. – Pratik Butani Oct 11 '13 at 04:54
  • 4
    +1 for after show()... Been at this for 2 hours and couldn't get it working until that. – Cruceo May 09 '14 at 15:16
  • 1
    @PratikButani it just a sample, for dynamic height you need to write certain algo like first calculate the height and width of the screen and then according to it you can sub divide the height and width of the dialog and its placement also. – PiyushMishra Sep 25 '14 at 05:38
  • Thanks but Very Late Reply :) @PiyushMishra – Pratik Butani Sep 25 '14 at 06:54
  • For me, dialog size changes only when I call setLayout() in dialog fragment's onResume() method. – Roger Huang Sep 18 '15 at 03:12
  • 1
    it's important to change the size AFTER the method show is called. It took me too long to realize that. – Alberto M Apr 18 '16 at 16:25
  • Problem: after alertDialog.getWindow().setLayout(600, 400) dialog survives rotations with primal size. Any way to restore default behaviour (close dialog on rotate)? – Grzegorz Dev Apr 06 '17 at 04:13
  • Better to use.... window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); Supports all device – NBaua Dec 08 '18 at 13:10
  • @NBaua Unless you used a different `LayoutParams` import (I used `ViewGroup.LayoutParams`, which was suggested by AndroidStudio), your suggestion doesn't work with version 1 of the answer: The dialog doesn't change size. – Neph Apr 28 '20 at 11:11
  • your way is better – Vijay Feb 03 '21 at 03:36
  • Hello, I'm using custom AlertDialog with recyclerView. My issue is I'm using gridlayoutmanager and the span count is 4. but when dialog opens items row has space right side and when I'm scrolling this space remove automatically. – Abhi S Apr 27 '22 at 04:20
31

Ok , I can control the width and height using Builder class. I used

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
builder.setTitle("Title");
AlertDialog alertDialog = builder.create();
alertDialog.getWindow().setLayout(600, 400); //Controlling width and height.
alertDialog.show();
Abdul Rizwan
  • 3,904
  • 32
  • 31
sat
  • 40,138
  • 28
  • 93
  • 102
24

For those who will find this thread like me, here is IMO better solution (note the 70% which sets min width of the dialog in percent of screen width):

<style name="my_dialog" parent="Theme.AppCompat.Dialog.Alert">
    <item name="windowMinWidthMajor">70%</item>
    <item name="windowMinWidthMinor">70%</item>
</style>

And then apply this style to dialog:

AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.my_dialog);
vovan888
  • 748
  • 6
  • 10
21

Before trying to adjust the size post-layout, first check what style your dialog is using. Make sure that nothing in the style tree sets

<item name="windowMinWidthMajor">...</item>
<item name="windowMinWidthMinor">...</item>

If that's happening, it's just as simple as supplying your own style to the [builder constructor that takes in a themeResId](http://developer.android.com/reference/android/app/AlertDialog.Builder.html#AlertDialog.Builder(android.content.Context, int)) available API 11+

<style name="WrapEverythingDialog" parent=[whatever you were previously using]>
    <item name="windowMinWidthMajor">0dp</item>
    <item name="windowMinWidthMinor">0dp</item>
</style>
tir38
  • 9,810
  • 10
  • 64
  • 107
  • 2
    How can I find the theme used by a dialog? I can just guess. – Leos Literak Sep 10 '16 at 18:23
  • crazy I know but I had to use BOTH `windowMinWidthMinor` and `android:windowMinWidthMinor` variations for this to work across different android versions... – hmac Feb 24 '23 at 12:53
13

This works as well by adding .getWindow().setLayout(width, height) after show()

alertDialogBuilder
            .setMessage("Click yes to exit!")
            .setCancelable(false)
            .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    // if this button is clicked, close
                    // current activity
                    MainActivity.this.finish();
                }
              })
            .setNegativeButton("No",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();
                }
            }).show().getWindow().setLayout(600,500);
Bartek Lipinski
  • 30,698
  • 10
  • 94
  • 132
Piotre98
  • 183
  • 1
  • 3
  • 12
13

If you wanna add dynamic width and height based on your device frame, you can do these calculations and assign the height and width.

 AlertDialog.Builder builderSingle = new 
 AlertDialog.Builder(getActivity());
 builderSingle.setTitle("Title");

 final AlertDialog alertDialog = builderSingle.create();
 alertDialog.show();

 Rect displayRectangle = new Rect();
 Window window = getActivity().getWindow();

 window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);

 alertDialog.getWindow().setLayout((int)(displayRectangle.width() * 
 0.8f), (int)(displayRectangle.height() * 0.8f));

P.S : Show the dialog first and then try to modify the window's layout attributes

Sid
  • 691
  • 6
  • 9
7

Appreciate answered by Sid because its dynamic but I want to add something.

What if you want to change width only, height will be as it is.

I have done like following:

    // All process of AlertDialog
    AlertDialog alert = builder.create();
    alert.show();

    // Creating Dynamic
    Rect displayRectangle = new Rect();

    Window window = getActivity().getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
    alert.getWindow().setLayout((int) (displayRectangle.width() *
            0.8f), alert.getWindow().getAttributes().height);

Here I used alert.getWindow().getAttributes().height to keep height as it is of AlertDialog and Width will be changed as per screen resolution.

Hope it will helps. Thanks.

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
4

I dont know whether you can change the default height/width of AlertDialog but if you wanted to do this, I think you can do it by creating your own custom dialog. You just have to give android:theme="@android:style/Theme.Dialog" in the android manifest.xml for your activity and can write the whole layout as per your requirement. you can set the height and width of your custom dialog from the Android Resource XML.

MegaMind
  • 336
  • 3
  • 8
  • It might work , but I did not want to add another activity. I posted the solution which I used. Thank you. – sat Dec 15 '10 at 07:21
  • Yep , the above method too works for showing items in popup style or say alert dialog style. Just tried it out in one of the projects. – sat Dec 15 '10 at 10:28
  • Just compared 2 ways , 1. With AlertDialog.builder and another 2. actvity with theme Dialog, second one is better solution , only drawback being if one has to send some results back to the background view , have to use startActivityForResult , since elements(views) in background activity are not available. – sat Dec 16 '10 at 11:11
4

I think tir38's answer is the cleanest solution. Have in mind that if you are using android.app.AlerDialog and holo themes your style should look like this

<style name="WrapEverythingDialog" parent=[holo theme ex. android:Theme.Holo.Dialog]>
    <item name="windowMinWidthMajor">0dp</item>
    <item name="windowMinWidthMinor">0dp</item>
</style>

And if using support.v7.app.AlertDialog or androidx.appcompat.app.AlertDialog with AppCompat theme your style should look like this

<style name="WrapEverythingDialog" parent=[Appcompat theme ex. Theme.AppCompat.Light.Dialog.Alert]>
    <item name="android:windowMinWidthMajor">0dp</item>
    <item name="android:windowMinWidthMinor">0dp</item>
</style>
user2610355
  • 101
  • 5
3
longButton.setOnClickListener {
  show(
    "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
      "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
      "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
      "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
      "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
      "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
      "1234567890-12345678901234567890123456789012345678901234567890"
  )
}

shortButton.setOnClickListener {
  show(
    "1234567890\n" +
      "1234567890-12345678901234567890123456789012345678901234567890"
  )
}

private fun show(msg: String) {
  val builder = AlertDialog.Builder(this).apply {
    setPositiveButton(android.R.string.ok, null)
    setNegativeButton(android.R.string.cancel, null)
  }

  val dialog = builder.create().apply {
    setMessage(msg)
  }
  dialog.show()

  dialog.window?.decorView?.addOnLayoutChangeListener { v, _, _, _, _, _, _, _, _ ->
    val displayRectangle = Rect()
    val window = dialog.window
    v.getWindowVisibleDisplayFrame(displayRectangle)
    val maxHeight = displayRectangle.height() * 0.6f // 60%

    if (v.height > maxHeight) {
      window?.setLayout(window.attributes.width, maxHeight.toInt())
    }
  }
}

short message

long message

Hun
  • 3,652
  • 35
  • 72
0

It took me a long time to get this working how I wanted it to. This code made it so that almost the whole screen width is filled with the dialog which is what I wanted...

public class GenericDialogFragment extends DialogFragment {
    
...

    public void show() {
        super.show(fragmentManager, null);

        // Wait for the dialog to be created before resizing
        // Source: https://stackoverflow.com/questions/8456143/dialogfragment-getdialog-returns-null
        fragmentManager.executePendingTransactions();

        // Creating dynamic size
        // Source: https://stackoverflow.com/questions/4406804/how-to-control-the-width-and-height-of-the-default-alert-dialog-in-android
        Rect displayRectangle = new Rect();

        Window window = mActivity.getWindow();
        window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);

        if (getDialog() != null) {
            getDialog().getWindow().setLayout(
                    (int) (displayRectangle.width() * 1.0f),
                    getDialog().getWindow().getAttributes().height);
        }
    }
}
AdamJ
  • 41
  • 2