天天看点

Android中的PopupWindow点击外侧区域取消

android中的PopupWindow是比较常用的控件,但是一些用户习惯的特性却没有成为PopupWindow的默认行为,需要手动去设置,比如点击外侧区域来将PopupWindow给dismiss掉.

网上有很多例子提供了解决办法,比较常见的是这样的:

PopupWindow pop = new PopupWindow(contentView, width, height);
	pop.setFocusable(true);
	pop.setOutsideTouchable(true);
	pop.setBackgroundDrawable(new BitmapDrawable());
	pop.showAtLocation(findViewById(R.id.parent), Gravity.CENTER, 0, 0);
           

这个方法可以解决点击取消的问题,不过有一点隐患,就是 BitmapDrawable的无参构造函数被deprecated了,在未来的版本中有失效的危险,可以用以下的方案来代替:

PopupWindow pop = new PopupWindow(contentView, screenWidth, screenHeight);
	Bitmap background = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
	pop.setBackgroundDrawable(new BitmapDrawable(getResources(), background));
	pop.setFocusable(true);
	pop.setOutsideTouchable(true);
	pop.showAtLocation(findViewById(R.id.parent), Gravity.CENTER, 0, 0);
           

继续阅读