几步实现Android 开发中的弹窗效果

可能你们常常用弹出对话框也就是AlertDialog来进项一些操做, html

今天咱们用另一种弹窗效果来完成 java

使用的到类PopupWindow android

官方说明: app

PopupWindow

extends Object

java.lang.Object ide

   ↳
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上的悬浮的容器, 动画

部分方法说明: spa

一、显示的方法: code

showAtLocation()显示在指定位置

showAsDropDown()显示在一个参照物View的周围

简单使用demo

一、建立一个字段

/*弹出的悬浮窗体*/
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);

/*或操做等于加操做*/
/*参数一、父窗体 参数二、布局控制 参数三、距离左边距离 参数四、距离顶部距离*/
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销毁前不将其销毁,就会产生错误
相关文章
相关标签/搜索