如何設(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í)行的纯露。
然而沈堡,事情并沒有這么簡(jiǎn)單坡锡。
按照這種方法顯示出來的dialog猴蹂,測(cè)量一下寬高之后院溺,發(fā)現(xiàn)dialog的寬高比我們?cè)O(shè)置的要小一點(diǎn)點(diǎn),而不是精確的相等磅轻。
進(jìn)行了好長(zhǎng)時(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);
以上摹量。