先上效果
这是一个简单的PopupWindow的设置,包括显示,布局,和外部半透明属性,下面来看具体实现:
1、popwindow初始化:
构造方法:
PopupWindow();
PopupWindow(int width, int height)
PopupWindow(View contentView, int width, int height)
PopupWindow(View contentView, int width, int height, boolean focusable)
方法:
setBackgroundDrawable(Drawable drawable) //该方法用于设置popupWindow的背景;
setOutsideTouchable() //用于设置popupwindow的点击外部消失,需配合setBackgroundDrawable()使用
显示的方法:
showAtLocation(View parent, int gravity, int x, int y) ;
showAsDropDown(View anchor)
showAsDropDown(View anchor, int xoff, int yoff)
showAsDropDown(View anchor, int xoff, int yoff, int gravity)
设置外部背景透明度:
WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 0.5f; //0.0-1.0 getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); getWindow().setAttributes(lp);
上代码:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_meg); initTopPop(); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bgAlpha(0.5f); popupWindow.showAtLocation(popView, Gravity.CENTER, 0, 0); } }); }private void initTopPop() { popView = LayoutInflater.from(this).inflate(R.layout.pop, null); popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); popupWindow.setBackgroundDrawable(new ColorDrawable(Color.GRAY)); popupWindow.setOutsideTouchable(true); popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { //popupwindow消失时使背景不透明 bgAlpha(1f); } }); }private void bgAlpha(float bgAlpha) { WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = bgAlpha; //0.0-1.0 getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); getWindow().setAttributes(lp); }