首先再刚开始的写的时候布局出现一些错误,明明再布局中写的是“”android:layout_width="match_parent"
但是页面中还是显示在正中央,左右俩边还是会出现问题,困扰很久,才解决,是因为我们如果使用布局中的`这个根布局<LinearLayout
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:orientation=“vertical”
>肯定是不行的,所以我们需要在给他写一个子布局的一个LinearLayout或者其他的
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<ImageView
android:id="@+id/iamge_fenxiang"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_300"
android:background="@drawable/fenxiang"
></ImageView>
</LinearLayout>
`
//我写的是pop从底部弹出
backgroundAlpha(0.5f);//让背景变暗
// 设置布局文件
final PopupWindow mPopupWindow = new PopupWindow(DynamicContentActivity.this);
View view = LayoutInflater.from(DynamicContentActivity.this).inflate(R.layout.aleart_fenxiang, null);
ImageView iamge_fenxiang = view.findViewById(R.id.iamge_fenxiang);
iamge_fenxiang.setScaleType(ImageView.ScaleType.FIT_XY);
mPopupWindow.setContentView(view);
//设置弹出和消失的动画
mPopupWindow.setAnimationStyle(R.style.showPopupAnimation);
// 为了避免部分机型不显示,我们需要重新设置一下宽高
mPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
mPopupWindow.setBackgroundDrawable(new ColorDrawable(0x0000000)); // 设置pop透明效果
mPopupWindow.setFocusable(true);// 设置pop获取焦点,如果为false点击返回按钮会退出当前Activity,如果pop中有Editor的话,focusable必须要为true
mPopupWindow.setTouchable(true); // 设置pop可点击,为false点击事件无效,默认为true
mPopupWindow.setOutsideTouchable(false);// 设置点击pop外侧消失,默认为false;在focusable为true时点击外侧始终消失
mPopupWindow.showAtLocation(view, Gravity.BOTTOM, Gravity.LEFT, Gravity.RIGHT);
//背景变暗消失监听
mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
backgroundAlpha(1);
}
});
// 点击窗体内其他地方消失
popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (popupWindow != null && popupWindow.isShowing()) {
backgroundAlpha(1);
popupWindow.dismiss();
popupWindow = null;
}
return false;
}
});
}```
//pop背景变暗
private void backgroundAlpha(float bgAlpha) {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = bgAlpha; //0.0-1.0
getWindow().setAttributes(lp);
}```