如何設(shè)置一個(gè)AlertDialog的尺寸?
很容易就可以查到,有這么一個(gè)做法:
How to control the width and height of the default Alert Dialog in Android?
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.
注意:setLayout是在show()之后執(zhí)行的。
然而,事情并沒有這么簡單。
按照這種方法顯示出來的dialog,測(cè)量一下寬高之后,發(fā)現(xiàn)dialog的寬高比我們?cè)O(shè)置的要小一點(diǎn)點(diǎn),而不是精確的相等。
進(jìn)行了好長時(shí)間的排查,最后確定,是alertDialog本身最大的View里面帶上了padding,這個(gè)是由默認(rèn)的style帶過來的。
當(dāng)時(shí)沒有找到在哪里設(shè)置這個(gè)padding,于是使用了一種折衷的方式來使得dialog和我們要求的size相等。
final AlertDialog alertDialog = builder.setView(R.layout.dialog).create();
alertDialog.show();
View decorView = alertDialog.getWindow().getDecorView();
int paddingTop = decorView.getPaddingTop();
int paddingBottom = decorView.getPaddingBottom();
int paddingLeft = decorView.getPaddingLeft();
int paddingRight = decorView.getPaddingRight();
int width = 600 + paddingLeft + paddingRight;
int height = 400 + paddingTop + paddingBottom;
alertDialog.getWindow().setLayout(width, height);
以上。