地址:https://juejin.cn/post/7021434436847665189
现象
当设置dialog的WindowManager.LayoutParams的width和height为WindowManager.LayoutParams.MATCH_PARENT的时候,dialog弹出后出现抖动。
代码如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
WindowManager.LayoutParams params = window.getAttributes();
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.MATCH_PARENT;
window.setAttributes(params);
}
原因
1 网上有人说是因为在上述代码在onShow()中调用的原因,将代码放在onCreate()即可。有上述情况的同学可以参考修改。
2 当前界面处于全屏状态(WindowManager.LayoutParams.FLAG_FULLSCREEN)。当显示dialog时,因为dialog没有同步设置全屏,导致在显示过程中界面会重新显示出状态栏,从而造成dialog显示的时候出现上下抖动的现象。
方案
针对原因二: 在创建dialog的时候判断当前界面是否为全屏,同步设置和当前界面一样的状态即可。
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class CustomDialog extends Dialog {
public CustomDialog(Context context) {
this(context, 0);
}
public CustomDialog(Context context, int themeResId) {
super(context, themeResId);
if (context instanceof Activity) {
setOwnerActivity((Activity) context);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
WindowManager.LayoutParams params = window.getAttributes();
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.MATCH_PARENT;
if (isFullScreen(getOwnerActivity())) {//判断是不是全屏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
window.setAttributes(params);
}
private boolean isFullScreen(Activity activity) {
if (activity == null) {
return false;
}
int flags = activity.getWindow().getAttributes().flags;
return (flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) ==
WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
}
网友评论