android popupwindow在屏幕内水平居中

方案一:写死window宽度,用屏幕大小减去window大小,X坐标偏移量除以2

if (mPopupWindow == null) {
    PopupwinTransTypeBinding mBinding = DataBindingUtil.inflate(LayoutInflater.from(mFragment.mActivity), R.layout.popupwin_trans_type, null, false);
    mPopupWindow = new PopupWindow(mBinding.getRoot(), 200, ViewGroup.LayoutParams.WRAP_CONTENT);
    mPopupWindow.setFocusable(true);
    mPopupWindow.setBackgroundDrawable(new ColorDrawable(0));
    mPopupWindow.setOutsideTouchable(true);
    mBinding.setTypeVM(new PopTypeVM(mFragment, mPopupWindow, mRepo));
}
ScreenUtil.setBackgroundAlpha(mFragment.mActivity, 0.7f);//设置窗口阴影
mPopupWindow.setOnDismissListener(() -> {
    ScreenUtil.setBackgroundAlpha(mFragment.mActivity, 1.0f);
});
int xPos = (ScreenUtil.getScreenWidth(mFragment.mActivity) - 200) / 2;
mPopupWindow.showAsDropDown(mBinding.llScreen, xPos, 0);
方案二:通过测量window宽度,计算偏移量。ps.第一次获取的数据总是不对
mPopupWindow.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int xPos = (ScreenUtil.getScreenWidth(mFragment.mActivity) - mPopupWindow.getContentView().getMeasuredWidth()) / 2;
mPopupWindow.showAsDropDown(mBinding.llScreen, xPos, 0);
方案三:布局文件根控件写成铺满全屏,背景设置空或者透明,内容部分设置屏幕居中。如果要实现点击窗体外消失,监听根布局。
这个办法有点蠢,效果是能实现的。

/**
 * 设置窗口透明度
 *
 * @param mContext
 * @param bgAlpha
 */
public static void setBackgroundAlpha(Context mContext, float bgAlpha) {
    WindowManager.LayoutParams lp = ((Activity) mContext).getWindow()
            .getAttributes();
    lp.alpha = bgAlpha;
    ((Activity) mContext).getWindow().setAttributes(lp);
}



/**
 * 获得屏幕高度
 */
public static int getScreenWidth(Context context) {
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics outMetrics = new DisplayMetrics();
    wm.getDefaultDisplay().getMetrics(outMetrics);
    return outMetrics.widthPixels;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值