隐藏状态栏后,如何让PopupWindow显示在屏幕最顶部?
解决Activity隐藏状态栏时PopupWindow顶部间隙问题
问题原因
当Activity隐藏状态栏后,PopupWindow的默认布局逻辑仍会预留状态栏高度的空间,即便调用showAtLocation(view, Gravity.NO_GRAVITY, 0, 0),也会出现顶部间隙。
解决方案
可以通过以下方式修复:
核心方案:设置PopupWindow忽略状态栏占位
在创建PopupWindow后,添加配置让它不受系统状态栏的影响,这是最直接的修复方式:
// 允许PopupWindow超出屏幕范围,避免被状态栏区域裁剪 popupWindow.setClippingEnabled(false); // 给PopupWindow的内容视图设置全屏布局flag WindowManager.LayoutParams params = (WindowManager.LayoutParams) contentView.getLayoutParams(); if (params == null) { params = new WindowManager.LayoutParams(); } params.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS; contentView.setLayoutParams(params);
修改后的完整代码示例
Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed(() -> { View contentView = LayoutInflater.from(this).inflate(R.layout.popup_window_content, null, false); PopupWindow popupWindow = new PopupWindow(this); popupWindow.setContentView(contentView); popupWindow.setHeight(ViewUtil.dp2px(getResources().getDimension(R.dimen.dp_79))); popupWindow.setWidth(ViewUtil.dp2px(getResources().getDimension(R.dimen.screen_width))); // 添加修复配置 popupWindow.setClippingEnabled(false); WindowManager.LayoutParams params = (WindowManager.LayoutParams) contentView.getLayoutParams(); if (params == null) { params = new WindowManager.LayoutParams(); } params.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS; contentView.setLayoutParams(params); View view = mBinding.bg; Log.d("debug", "pos: "+view.getX()+" "+view.getY()); popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, 0); }, 1000);
内容的提问来源于stack exchange,提问作者ei zao
相关产品推荐
相关产品推荐

