本例是以点击ListView中的条目时在对应的条目位置弹出popupWindow
//获得popupWindow的充气视图
View contentView = View.inflate(context, R.layout.popup_app_manager, null);
//创建PopupWindow对象
//参数1:要弹出的View
//参数2:width 宽
//参数3:height高
PopupWindow popupWindow = new PopupWindow(contentView,ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
//用于存放ListView中的ItemView在左上角在幕屏上的x , y坐标
int[] location = new int[2];
//itemView为ListView的条目,把location传入其中使其赋值
itemView.getLocationInWindow(location);
//点击popupWindow背景的时候关闭popupWindow
popupWindow.setOutsideTouchable(true);//设置popupWindow可触摸
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//设置背景颜色为透明
//给PopupWindow指定动画
popupWindow.setAnimationStyle(R.style.PopupWindowAnimation);
//在指定的位置弹出popupWindow
//parent父控件
//gravity对齐方式
//x y 坐标
popupWindow.showAtLocation(parent, Gravity.LEFT | Gravity.TOP, location[0] + 50, location[1] + 20);
下面是popupWindow的动画文件,在anim夹(没有该文件夹则新建之)中新建一个名为popup_enter.xml的文件作为入场动画
<set xmlns="android........
android:shareInterpolator="false">
<translate
android:fromXDelta="0"
android:toXDelta="100%"
android:duration="300"/>
<alpha
android:fromAlpha="1"
android:toAlpha="0"
duration="200"/>
</set>
popup_exit.xml出场动画:
<set xmlns="android........"
android:shareInterpolator="false">
<translate
android:fromXDelta="100%"
android:toXDelta="0"
android:duration="300"/>
<alpha
android:fromAlpha="0"
android:toAlpha="1"
duration="200"/>
</set>
然后在样式style.xml文件中:
<style name="popupWindowAnimation">
<item name="android:windowEnterAnimation">@anim/popup_enter</item>
<item name="android:windowExitAnimation">@anim/popup_exit</item>
</style>