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

AndroidAndroid Widget

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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);

Solution 2 - Android

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();

Solution 3 - Android

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);

Solution 4 - Android

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>

Solution 5 - Android

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);

Solution 6 - Android

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

Solution 7 - Android

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.

Solution 8 - Android

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.

Solution 9 - Android

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>

Solution 10 - Android

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

Solution 11 - Android

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);
        }
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsatView Question on Stackoverflow
Solution 1 - AndroidPiyushMishraView Answer on Stackoverflow
Solution 2 - AndroidsatView Answer on Stackoverflow
Solution 3 - Androidvovan888View Answer on Stackoverflow
Solution 4 - Androidtir38View Answer on Stackoverflow
Solution 5 - AndroidPiotre98View Answer on Stackoverflow
Solution 6 - AndroidSidView Answer on Stackoverflow
Solution 7 - AndroidPratik ButaniView Answer on Stackoverflow
Solution 8 - AndroidMegaMindView Answer on Stackoverflow
Solution 9 - Androiduser2610355View Answer on Stackoverflow
Solution 10 - AndroidChanghoonView Answer on Stackoverflow
Solution 11 - AndroidAdamJView Answer on Stackoverflow