Android中我们很经常使用popwindow,这里说下popwindow的最基本使用方法
首先要先创建一个popwindow对象
PopupView popupView = new PopupView(this);
final PopupWindow mPopupWindow = new PopupWindow(popupView, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT,true);
//设置背景透明才能显示
mPopupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
mPopupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
注意:这里要设置它的背景颜色为透明,这样popwindow才能显示,PopupView是我们自定义的一个View,是popwindow要显示的内容。
接着 我们要设置当弹出Popwindow时Activity背景变灰,这里我们封装了一个方法,通过传一个背景灰度比例值来实现背景颜色改变
/**
* 改变背景颜色
*/
private void darkenBackground(Float bgcolor){
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = bgcolor;
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
getWindow().setAttributes(lp);
}
darkenBackground(0.2f);
实现灰色半透明背景
最后在设置Popwindow的关闭监听,当popwindow关闭时我们把背景变回去
mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
darkenBackground(1f);
}
});