How to control the width and height of the default Alert Dialog in 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);
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();
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);
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>
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);