PopupWindow详解

发布时间:2020-06-29 11:36:32 作者:joyy001
来源:网络 阅读:381

Android的对话框有两种:PopupWindow和AlertDialog。它们的不同点在于:

AlertDialog的位置固定,而PopupWindow的位置可以随意
AlertDialog是非阻塞线程的,而PopupWindow是阻塞线程的


下面介绍PopupWindow的用法:

PopupWindow的位置按照有无偏移分,可以分为偏移和无偏移两种;按照参照物的不同,可以分为相对于某个控件和相对于父控件

showAsDropDown(View anchor):相对某个控件的位置(正左下方),无偏移
showAsDropDown(View anchor, int xoff, int yoff):相对某个控件的位置,有偏移
showAtLocation(View parent, int gravity, int x, int y):相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移


具体代码:

private void showPopupWindow(View v) {  //v为父控件
View inflate = LayoutInflater.from(getActivity()).inflate(
				R.layout.pop_del, null); //定义一个布局
		mPopupWindow = new PopupWindow(inflate, 140, 40); //传入布局,及Popupwindow的宽高
		//如果要实现点击PopupWindow之外的区域,关闭PopupWindow,要增加下面这3个属性
		mPopupWindow.setFocusable(true);
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		//PopupWindow弹出及关闭动画
		mPopupWindow.setAnimationStyle(R.style.PopAnim);
		int[] location = new int[2];
		v.getLocationOnScreen(location); //获取父控件在屏幕上的位置坐标
		//将Popupwindow显示在父控件的左边,location[0]为父控件的横坐标,location[1]为父控件的纵坐标
		mPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0]
				- mPopupWindow.getWidth(), location[1]);
		//设置布局的点击监听,点击PopupWindow之外的区域,关闭PopupWindow	
		inflate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			if(mPopupWindow != null){
				mPopupWindow.dismiss();
				mPopupWindow = null;
			}
			}
		});

}


mPopupWindow.setFocusable(false):说明PopuWindow不能获得焦点,即使设置设置了背景不为空也不能点击外面消失,只能由dismiss()消失,但是外面的View的事件还是可以触发,back键也可以顺利dismiss掉。

当设置为popuWindow.setFocusable(true);的时候,加上下面两行设置背景代码,点击外面和Back键才会消失

mPopupWindow.setOutsideTouchable(true):设置显示PopuWindow之后在外面点击是否有效。如果为false的话,那么点击PopuWindow外面并不会关闭PopuWindow。当然这里很明显只能在Touchable下才能使用。

要让PopUpWindow dimiss(即点击PopuWindow之外的地方此或者back键PopuWindow会消失),PopUpWindow的背景不能为空。必须在popuWindow.showAsDropDown(v);或者其它的显示PopuWindow方法之前设置它的背景不为空:mPopupWindow.setBackgroundDrawable(new BitmapDrawable());


推荐阅读:
  1. PopupWindow简单用法
  2. PopupWindow整理

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

对话框 android parent

上一篇:java中静态方法和非静态方法有区别吗

下一篇:java中的抽象是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》