PopUpWindow使用详解

学习网站:

http://blog.csdn.net/harvic880925/article/details/49272285

http://blog.csdn.net/harvic880925/article/details/49278705

http://blog.csdn.net/celester_best/article/details/53445827

1、构造函数

public PopupWindow (Context context)  

public PopupWindow(View contentView)   

public PopupWindow(View contentView, int width, int height)  

public PopupWindow(View contentView, int width, int height, boolean focusable) 

 

首要注意:看这里有四个构造函数,但要生成一个PopupWindow最基本的三个条件是一定要设置的:View contentView,

int width, int height ;少任意一个就不可能弹出来PopupWindow!!!!

所以,如果使用方法一来构造PopupWindow,那完整的构造代码应该是这样的:

  1. View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popuplayout, null);  
  2. PopupWindwo popWnd = PopupWindow (context);  
  3. popWnd.setContentView(contentView);  
  4. popWnd.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);  
  5. popWnd.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);  

这里说一下为什么样强制设置contentView;很简单的原因是因为PopupWindow没有默认布局,它不会像AlertDialog那样只setTitle,就能弹出来一个框。PopupWindow是没有默认布局的,它的布局只有通过我们自己设置才行。

  1. 显示函数
  1. //相对某个控件的位置(正左下方),无偏移  
  2. showAsDropDown(View anchor):  
  3. //相对某个控件的位置,有偏移;xoff表示x轴的偏移,正值表示向左,负值表示向右;yoff表示相对y轴的偏移,正值是向下,负值是向上;  
  4. showAsDropDown(View anchor, int xoff, int yoff):  
  5. //相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移  
  6. showAtLocation(View parent, int gravity, int x, int y): 

 

其它函数

popupWindow.setTouchable(true);//是否响应touch事件,默认是true,如果设置为false,所有touch事件无响应,包括点击事件。

popupWindow.setTouchInterceptor(new OnTouchListener()/当PopupWindow被触碰时的回调方法

public boolean onTouch(View v, MotionEvent event) {

这里如果返回true的话,touch事件将被拦截拦截后PopupWindow的onTouchEvent不被调用,这样点击外部区域无法dismiss

         return false;

popupWindow.setOutsideTouchable(true);//PopupWindow以外的区域是否可点击,点击后是否会消失。

setFocusable(true);//设置PopupWindow可获得焦点  

popupWindow.setOnDismissListener(new OnDismissListener() {//PopupWindow消失时的监听

mPopWindow.setBackgroundDrawable(new BitmapDrawable())// 如果不设置PopupWindow的背景,无论是点击外部区域还是Back键都无法dismiss弹框

猜你喜欢

转载自blog.csdn.net/xxdw1992/article/details/82769646
今日推荐