方案一:寫死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;
}