PopupWindow弹出框且背景变暗

public void showPopupWindow(View view) {

// 一个自定义的布局,作为显示的内容
View contentView = LayoutInflater.from(this).inflate(
R.layout.xxxx, null);

final PopupWindow popupWindow = new PopupWindow(contentView,
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);//刚开始没注意调整宽度和高度,布局总不对


ImageView detail = (ImageView) contentView.findViewById(R.id.xxxx);
detail.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
popupWindow.dismiss(); 

}
});

ImageView iKnow = (ImageView) contentView.findViewById(R.id.xxxx);
iKnow.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
popupWindow.dismiss(); 
}
});

popupWindow.setTouchable(true);

popupWindow.setTouchInterceptor(new OnTouchListener() {


@Override
public boolean onTouch(View v, MotionEvent event) {
// 这里如果返回true的话,touch事件将被拦截
// 拦截后 PopupWindow的onTouchEvent不被调用,这样点击外部区域无法dismiss
return false;
}
});


// 如果不设置PopupWindow的背景,无论是点击外部区域还是Back键都无法dismiss弹框
popupWindow.setBackgroundDrawable(getResources().getDrawable(
R.drawable.xxxx));
//如果没有背景,则可以用
//popupWindow.setBackgroundDrawable(new BitmapDrawable());
//popupWindow.setOutsideTouchable(true);

//pop window居中显示
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);


ColorDrawable cd = new ColorDrawable(0x000000);
popupWindow.setBackgroundDrawable(cd);
// 产生背景变暗效果
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 0.4f;
getWindow().setAttributes(lp);
popupWindow.setOnDismissListener(new OnDismissListener() {


// 在dismiss中恢复透明度
public void onDismiss() {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 1f;
getWindow().setAttributes(lp);
}
});


}

你可能感兴趣的:(PopupWindow弹出框且背景变暗)