`
ipjmc
  • 浏览: 703181 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

显示PopupWindow

阅读更多
        PopupWindow可以实现浮层效果,而且可以自定义显示位置,出现和退出时的动画,比如新浪微博顶部栏的微博分组就是用PopupWindow实现的。

        一、实例化PopupWindow,这里用R.layout.group_list填充mPopupWindow,并指定宽高。

mPopupLayout = getLayoutInflater().inflate(R.layout.group_list, null);
mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.transparent)); //必须为PopupWindow设置一个背景,点击其他区域才能让PopupWindow消失
mPopupWindow = new PopupWindow(mPopupLayout, width, height, true);

        二、指定PopupWindow的显示位置
//mAncorView是页面中的某个View,默认是将mPopupWindow与mAncorView的左下角对齐,如果空间不够显示,则将将mPopupWindow与mAncorView的左上角对齐。offsetX和offsetY是mPopupWindow位置的相对偏移,很容易理解。
		mPopupWindow.showAsDropDown(mAncorView, offsetX, offsetY);


也可使用下面方法
//下面的方法是用屏幕上的绝对坐标显示,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


        三、为PopupWindow指定动画
先定义动画
PopupWindow出现时的动画,popup_enter.xml

<?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>


PopupWindow消失时的动画,popup_exit.xml
<?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>


再设定动画的style
<style name="PopupAnimation" parent="android:Animation">
    <item name="android:windowEnterAnimation">@anim/popup_enter</item>
    <item name="android:windowExitAnimation">@anim/popup_exit</item>
</style>


最后通过Java代码设置动画
mPopupWindow.setAnimationStyle(R.style.PopupAnimation);
分享到:
评论
1 楼 yahier 2012-12-04  
  为什么我的popupwindow 有时不显示呢。经过测试 他被显示了  但就是不可见。里面装载的view的可见的啊  神奇啊啊

相关推荐

Global site tag (gtag.js) - Google Analytics