[size=medium] PopupWindow可以实现浮层效果,而且可以自定义显示位置,出现和退出时的动画,比如新浪微博顶部栏的微博分组就是用PopupWindow实现的。
一、实例化PopupWindow,这里用R.layout.group_list填充mPopupWindow,并指定宽高。[/size]
[size=medium]二、指定PopupWindow的显示位置[/size]
[size=medium]也可使用下面方法[/size]
[size=medium]三、为PopupWindow指定动画
先定义动画
PopupWindow出现时的动画,popup_enter.xml[/size]
[size=medium]PopupWindow消失时的动画,popup_exit.xml[/size]
[size=medium]再设定动画的style[/size]
[size=medium]最后通过Java代码设置动画[/size]
一、实例化PopupWindow,这里用R.layout.group_list填充mPopupWindow,并指定宽高。[/size]
mPopupLayout = getLayoutInflater().inflate(R.layout.group_list, null);
mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.transparent)); //必须为PopupWindow设置一个背景,点击其他区域才能让PopupWindow消失
mPopupWindow = new PopupWindow(mPopupLayout, width, height, true);
[size=medium]二、指定PopupWindow的显示位置[/size]
//mAncorView是页面中的某个View,默认是将mPopupWindow与mAncorView的左下角对齐,如果空间不够显示,则将将mPopupWindow与mAncorView的左上角对齐。offsetX和offsetY是mPopupWindow位置的相对偏移,很容易理解。
mPopupWindow.showAsDropDown(mAncorView, offsetX, offsetY);
[size=medium]也可使用下面方法[/size]
//下面的方法是用屏幕上的绝对坐标显示,mPopupWindow
//我们往往不知道mPopupWindow要显示的精确位置,通常先计算页面上某个元素mView的位置,在进行偏移
//得到mView在屏幕中的坐标
int [] pos = new int[2];
mView.getLocationOnScreen(pos);
offsetY = pos[1] + mView.getHeight();
offsetX = 0;
//显示mPopupWindow
mPopupWindow.showAtLocation(mView, Gravity.TOP|Gravity.CENTER_HORIZONTAL, offsetX, offsetY);//这里的第一个参数没搞明白什么用,android官方文档说是为了获取token
[size=medium]三、为PopupWindow指定动画
先定义动画
PopupWindow出现时的动画,popup_enter.xml[/size]
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale android:fromXScale="1.0" android:toXScale="1.0"
android:fromYScale="0" android:toYScale="1.0"
android:pivotX="50%" android:pivotY="0%"
android:duration="100" />
</set>
[size=medium]PopupWindow消失时的动画,popup_exit.xml[/size]
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:fromXScale="1.0" android:toXScale="1.0"
android:fromYScale="1.0" android:toYScale="0"
android:pivotX="50%" android:pivotY="0%"
android:duration="50" />
</set>
[size=medium]再设定动画的style[/size]
<style name="PopupAnimation" parent="android:Animation">
<item name="android:windowEnterAnimation">@anim/popup_enter</item>
<item name="android:windowExitAnimation">@anim/popup_exit</item>
</style>
[size=medium]最后通过Java代码设置动画[/size]
mPopupWindow.setAnimationStyle(R.style.PopupAnimation);