标签:
最近尝试使用popupWindow实现背景变暗效果,自己优化了一下,并封装成一个可以调用的方法,默认实现弹出窗口显示在传入view的下方,以下代码有详细注释,有问题可以留言
展示效果如下:
/**
* 我封装的这个popupwindow的方法,
* 第一个参数是他要显示在哪个控件下面
* 第二个参数是要填充到popupWindow中的布局文件id
* 第三个参数是要给popupWindow设置的背景资源id
*/
private void showPopWindow(View v,int convertViewResource,int drawbelResource) {
//创建一个popUpWindow
if (popupWindow == null) {
View popLayout = LayoutInflater.from(getActivity()).inflate(convertViewResource, null);
//给popUpWindow内的空间设置点击事件
popLayout.findViewById(R.id.tv_pop_notice).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), FindGuanzhuActivity.class);
startActivity(intent);
}
});
popLayout.findViewById(R.id.tv_pop_group).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), GroupFindActivity.class);
startActivity(intent);
}
});
//实例化一个popupWindow
popupWindow = new PopupWindow(popLayout, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
//产生背景变暗效果
WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
lp.alpha = 0.4f;
getActivity().getWindow().setAttributes(lp);
//点击外面popupWindow消失
popupWindow.setOutsideTouchable(true);
//popupWindow获取焦点
popupWindow.setFocusable(true);
//popupWindow设置背景图
Drawable drawable = getResources().getDrawable(drawbelResource);
popupWindow.setBackgroundDrawable(drawable);
//popupWindow设置开场动画风格
//popupWindow.setAnimationStyle(R.style.popupWindow_anim);
//刷新popupWindow
//popupWindow.update();
//设置popupWindow消失时的监听
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//在dismiss中恢复透明度
public void onDismiss() {
WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
lp.alpha = 1f;
getActivity().getWindow().setAttributes(lp);
}
});
popupWindow.showAsDropDown(v);
}else {
//如果popupWindow正在显示,接下来隐藏
if (popupWindow.isShowing()) {
popupWindow.dismiss();
}else {
//产生背景变暗效果
WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
lp.alpha = 0.4f;
getActivity().getWindow().setAttributes(lp);
popupWindow.showAsDropDown(v);
}
}
`
}
popupWindow弹出窗口的完美实现(实现弹出背景变暗效果)
标签:
原文地址:http://blog.csdn.net/qq_33416180/article/details/51337016