AlertDialog的尺寸問題

如何設(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);

以上。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容