How to control the width and height of the default Alert Dialog in Android?
Asked Answered
A

11

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?

Andradite answered 10/12, 2010 at 8:4 Comment(0)
S
228

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);
Stylistic answered 3/8, 2011 at 7:15 Comment(15)
Can you center the text doing this?Auctioneer
@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.Stylistic
@amit yes you can lp can control anything.Stylistic
Thanks. The second solution works fine for me, the first one doesn't. Tested with Android API 17.Abstruse
@Stylistic How to set height and width which support to all Device.Osber
+1 for after show()... Been at this for 2 hours and couldn't get it working until that.Glue
@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.Stylistic
Thanks but Very Late Reply :) @StylisticOsber
For me, dialog size changes only when I call setLayout() in dialog fragment's onResume() method.Silvestro
it's important to change the size AFTER the method show is called. It took me too long to realize that.Thermostat
Problem: after alertDialog.getWindow().setLayout(600, 400) dialog survives rotations with primal size. Any way to restore default behaviour (close dialog on rotate)?Blintz
Better to use.... window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); Supports all deviceCreese
@Creese 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.Marlie
your way is betterOubliette
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.Mosher
A
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();
Andradite answered 15/12, 2010 at 7:22 Comment(4)
Excellent catch. After create() is WAY better than after show(), espectially if using DialogFragments!Teacart
You are not using the builder class to change the width/height, just the alertDialog objectDizon
it didn't work for me between the create and the show, but only after the show.Thermostat
Should set the window width in an on show listener.Lippert
W
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);
Wampum answered 3/4, 2019 at 18:50 Comment(4)
Using of percentage with style is much more easier than making it programmaticallyManslaughter
Not working. same width even after this Style.Farahfarand
This can (if at all) only control the minimum width, not the actual or the maximum width.Bosket
crazy I know but I had to use BOTH windowMinWidthMinor and android:windowMinWidthMinor variations for this to work across different android versions...Zoography
L
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>
Logicize answered 11/11, 2015 at 19:35 Comment(2)
How can I find the theme used by a dialog? I can just guess.Musquash
crazy I know but I had to use BOTH windowMinWidthMinor and android:windowMinWidthMinor variations for this to work across different android versions...Zoography
K
15

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

Keever answered 9/3, 2018 at 21:8 Comment(2)
What if I dont want to change height?Osber
"P.S : Show the dialog first and then try to modify the window's layout attributes" work like charm!Czarism
C
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);
Chintzy answered 12/8, 2014 at 8:18 Comment(1)
exactly AFTER show()! I tried before show() and failedBabyblueeyes
O
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.

Osber answered 28/11, 2018 at 7:33 Comment(0)
R
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.

Roadside answered 15/12, 2010 at 6:57 Comment(3)
It might work , but I did not want to add another activity. I posted the solution which I used. Thank you.Andradite
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.Andradite
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.Andradite
L
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>
Lingonberry answered 28/2, 2019 at 10:2 Comment(1)
you just copied tir38's answerMinute
D
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

Doris answered 19/7, 2019 at 1:22 Comment(0)
M
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://mcmap.net/q/27120/-dialogfragment-getdialog-returns-null
        fragmentManager.executePendingTransactions();

        // Creating dynamic size
        // Source: https://mcmap.net/q/27084/-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);
        }
    }
}
Millwork answered 14/10, 2021 at 3:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.