场景
由于项目需求,需要定制对话框,主要是圆角、背景色、尺寸变小。在网上,翻阅资料以及星火GPT的帮助下,没能成功解决对话框宽高问题(而且gpt的代码还出错了,AlertDialog.Builder里根本没有设置LayoutParams的方法。对的没有错,去官网developers查了一下,就是没有)
原因
小伙伴们以后在遇到修改AlertDialog的界面宽高的问题时,要注意在show函数调用之后修改window的宽高。否则,改动无法生效。即:
AlertDialog dialog = new AlertDialog.Builder(getActivity()).create().show();
Window window = dialog.getWindow();
//width 你想要的宽度; height 你想要的高度
window.setLayout(width, height);
通过翻阅源码
//这个是DialogFragment中的show方法。该方法的做的是在向Dialog中添加需要显示的fragment
public int show(FragmentTransaction transaction, String tag) {
mDismissed = false;
mShownByMe = true;
transaction.add(this, tag);
mViewDestroyed = false;
mBackStackId = transaction.commit();
return mBackStackId;
}
而AlertDialog的show()方法
//这里源码的注释是这样的:Start the dialog and display it on screen.即将dialog呈现在手机屏幕上。
public void show() {
if (mShowing) {
if (mDecor != null) {
if (mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
mWindow.invalidatePanelMenu(Window.FEATURE_ACTION_BAR);
}
mDecor.setVisibility(View.VISIBLE);
}
return;
}
mCanceled = false;
if (!mCreated) {
dispatchOnCreate(null);
} else {
// Fill the DecorView in on any configuration changes that
// may have occured while it was removed from the WindowManager.
final Configuration config = mContext.getResources().getConfiguration();
mWindow.getDecorView().dispatchConfigurationChanged(config);
}
onStart();
mDecor = mWindow.getDecorView();
if (mActionBar == null && mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
final ApplicationInfo info = mContext.getApplicationInfo();
mWindow.setDefaultIcon(info.icon);
mWindow.setDefaultLogo(info.logo);
mActionBar = new WindowDecorActionBar(this);
}
WindowManager.LayoutParams l = mWindow.getAttributes();
boolean restoreSoftInputMode = false;
if ((l.softInputMode
& WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) == 0) {
l.softInputMode |=
WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
restoreSoftInputMode = true;
}
mWindowManager.addView(mDecor, l);
if (restoreSoftInputMode) {
l.softInputMode &=
~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
}
mShowing = true;
sendShowMessage();
}
所以二者其实并不冲突,一个是在展示dialog,另一个是在展示dialog中的fragment内容。如果AlertDialog不调用show方法,则我们得到的dialog窗口时没有办法修改尺寸的值得。通过打日志,会发现width=-1。说明在分配宽度的时候,没能正确的分配。
结论
如果想要设置AlertDialog的宽高尺寸,一定要在dialog调用show方法之后修改。否则无效。