可能大家经常用弹出对话框也就是AlertDialog来进项一些操作,
今天我们用另外一种弹窗效果来完成
使用的到类PopupWindow
官方说明:
PopupWindow extends
Object
↳
android.widget.PopupWindow
Class Overview
A popup window that can be used to display an arbitrary view. The popup window is a floating container that appears on top of the current activity.
一个 弹出窗口可以被使用去展示一个任意的视图,这个弹出窗口是一个出现在当前activity上的悬浮的容器,
部分方法说明:
1、显示的方法:
showAtLocation()显示在指定位置
showAsDropDown()显示在一个参照物View的周围
简单使用demo
1、创建一个字段
/*弹出的悬浮窗体*/
private PopupWindow popupWindow;
//将关闭popupWindow窗口的操作封装为一个函数
dismissPopupWindow(popupWindow);
View contentView = View.inflate(getApplicationContext(), R.layout.popup_app_item, null);
/*-2代表包裹内容 -1代表填充父窗体*/
popupWindow = new PopupWindow(contentView, -2, -2);
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
int[] location = new int[2];
view.getLocationInWindow(location);
/*或操作等于加操作*/
/*参数1、父窗体 参数2、布局控制 参数3、距离左边距离 参数4、距离顶部距离*/
int dip = 60;
int px = DensityUtil.dip2px(getApplicationContext(), dip);
popupWindow.showAtLocation(parent, Gravity.LEFT | Gravity.TOP, px, location[1]);
/*popopWindow要求动画效果的播放必须要求窗体有背景颜色*/
/*弹出动画*/
ScaleAnimation scaleAnimation = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnimation.setDuration(500);
/*透明度*/
AlphaAnimation alphaAnimation = new AlphaAnimation(0.5f, 1.0f);
alphaAnimation.setDuration(500);
AnimationSet animationSet = new AnimationSet(false);
animationSet.addAnimation(scaleAnimation);
animationSet.addAnimation(alphaAnimation);
contentView.startAnimation(animationSet);
关闭窗体的函数
private void dismissPopupWindow(PopupWindow popupWindow) {
/*弹出窗体*/
if (popupWindow != null && popupWindow.isShowing()) {
popupWindow.dismiss();
popupWindow = null;
}
}
注意事项:
@Override
protected void onDestroy() {
dismissPopupWindow(popupWindow);
super.onDestroy();
}
在destroy方法中要将其关闭销毁,否则会报错,因为其依赖于父Activity的存在而存在,当activity销毁前不将其销毁,就会产生错误