在开发中我们经常遇到PopupWindow从底部弹出的情况,比如从底部向上弹出分享按钮、菜单等等,下面先上效果图:
一、首先简单介绍一下PopupWindow的使用:
1、首先看一下 构造函数(一共5个):
public PopupWindow()
public PopupWindow(View contentView)
public PopupWindow(int width, int height)
public PopupWindow(View contentView, int width, int height)
public PopupWindow(View contentView, int width, int height, boolean focusable)
本人比较习惯用三个参数或四个参数的构造,ps:用其他的也可以(可以用 对象.setXXX方法进行设置),如:
1 PopupWindowm
PopupWindow = new PopupWindow(contentView, width, height, focusable);
1 PopupWindow mPopupWindow = newPopupWindow();
2 mPopupWindow.setContentView(contentView);
3 mPopupWindow.setWidth(width);
4 mPopupWindow.setHeight(height);
5 mPopupWindow.setFocusable(focusable);
上面的1行代码 和 下面的5行代码 产生的效果相同的 ,我们分别说一下4个参数的含义
/**
* @param contentView the popup's //contentPopupWindow的布局文件
* @param width the popup's width //PopupWindow的宽
* @param height the popup's height //PopupWindow的高
* @param focusable true if the popup canbe focused, false otherwise //PopupWindow是否获取焦点(具体表现为其中EditText是否可以编辑)
*/
好了现在PopupWindow的准备工作完成了,下一步就是让我们的PopupWindow显示出来了
PopupWindow 显示的方法有两种:showAsDropDown(显示在相对于某个控件的位置)和showAtLocation(显示在相对于整个屏幕的位置):
mPopupWindow.showAsDropDown(Button对象);
mPopupWindow.showAtLocation(findViewById(R.id.linear_parent),Gravity.BOTTOM,0,0); //其中linear_parent是activity最外层LinearLayout的id
二、PopupWindow效果篇
我们的PopupWindow已经可以显示出来了,怎样可以实现点击空白处让我们的PopupWindow消失呢?只需要加上下面这行代码就可以了(具体原理博主也不知道,请各位明白的看官不吝赐教):
mPopupWindow.setBackgroundDrawable(newBitmapDrawable(getResources(), (Bitmap) null));
可是到了这里,我们的PopupWindow弹出时的效果跟我们常见的还是不太一样啊,不用担心,让我们来看一下,原来PopupWindow可以设置动画样式,我们只需要自己定义一下我们需要的动画就可以了,下面是代码:
具体应该是这样:
mPopupWindow.setAnimationStyle(R.style.anim_bottom_pop);
首先我们要在res目录下建一个anim目录(存放我们需要的动画效果)
然后新建两个xml文件 分别为:
bottom_pop_in.xml
<?xm version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="250"
android:fromYDelta="100.0%"
android:toYDelta="0.0" />
</set>
bottom_pop_out.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="250"
android:fromYDelta="100.0%"
android:toYDelta="0.0" />
</set>
然后我们还需要在res/values/styles中定义一个style
<style name="anim_bottom_pop">
<item name="android:windowEnterAnimation">@anim/bottom_pop_in</item>
<item name="android:windowExitAnimation">@anim/bottom_pop_out</item>
</style>
好了大功告成了,现在我们在调用showAsDropDown 和 showAtLocation 时,我们的PopupWindow就会自动加载动画效果了。
PS:本人是一枚小菜,错误之处欢迎各位大虾斧正
Demo地址:https://github.com/zhiweiSunday/PopupWindowDemo