转载请注明出处:http://blog.csdn.net/forevercbb/article/details/51354791
PopWindow在自定义菜单或者自定义弹出控件时比较常用,相对于其它的控件,PopWindow有较高可定制程度,可以实现更多的效果。但是PopWindow使用时容易出现一些不符合预期的问题,比如点击外部PopWindow不消失,点击菜单PopWindow消失了又出现等等。这是因为有的属性不易理解。这里分享一个利用PopWindow自定义了底部弹出菜单的demo,当然也可以通过位置的设置改变为系统菜单那样弹出,总之就是利用PopWindow实现的一个弹出框。模拟了系统菜单,点击菜单时弹出框消失,在点击事件中定义,如下。
if (popMenu != null && popMenu.isShowing()) {
popMenu.dismiss();
}
点击PopWindow外部,PopWindow消失。点击菜单弹出PopWindow,再点击菜单PopWindow消失。PopWindow弹出时,Activity变暗,实现被部分遮挡的效果。
if (popMenu == null) {
View popView = getActivity().getLayoutInflater().inflate(R.layout.pop_menu_layout, null);
popMenu = new PopupWindow(popView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
//findViewById
TextView cancer = (TextView) popView.findViewById(R.id.pop_cancer);
popMenu.setAnimationStyle(R.style.popWindow_animation);
popMenu.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {
// PopWindow消失的时候还原activity的透明度
WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
lp.alpha = 1f;
getActivity().getWindow().setAttributes(lp);
}
});
//设置点击监听
cancer.setOnClickListener(this);
//设置这几个属性实现点击外部消失
popMenu.setOutsideTouchable(true);
popMenu.setFocusable(true);
popMenu.setBackgroundDrawable(new BitmapDrawable());//设置背景,必须设置。
popMenu.update();
//设置PopWindow的位置,本例为底部弹出,类似于底部菜单样式。
popMenu.showAtLocation(mRootView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//设置Activity的alpha值为0.7f,模拟弹出PopWindow时背景暗淡的效果
WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
lp.alpha = 0.7f;
getActivity().getWindow().setAttributes(lp);
} else if (popMenu.isShowing()) {
popMenu.dismiss();
} else {
popMenu.showAtLocation(mRootView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
lp.alpha = 0.7f;
getActivity().getWindow().setAttributes(lp);
}