您的位置:首页 > 移动开发 > Android开发

Android开发:自己开发的一款通用弹窗库

2015-08-04 14:21 459 查看
基于popupWindow***了这个库,可以实现在按钮下面弹出弹窗,在按钮上面弹出弹窗,或者在页面的底部或者顶部弹出弹窗,弹窗都带有动画效果,另外默认点击弹窗外面区域,自动关闭弹窗,也可以关闭该功能,请先看效果图:



使用方法

添加依赖

[code]dependencies {
    compile 'cn.weidongjian.android:popupWindowHelper:0.5'
}


在项目的build.gradle中添加如上一行代码,就可以把库文件包含在你的项目中了

初始化

[code]private PopupWindowHelper popupWindowHelper;
private View popView;
popView = LayoutInflater.from(this).inflate(R.layout.popupview, null);
        popupWindowHelper = new PopupWindowHelper(popView);


popView就是要弹窗的视图,可以自己在xml中定义

在按钮的上方显示弹窗

[code]popupWindowHelper.showAsPopUp(view);


其中view接受点击事件的按钮

在按钮的下方显示弹窗

[code]popupWindowHelper.showAsDropDown(view);


这个调用的是popupWindow的原生方法,没什么可说的

从顶部下拉显示

[code]popupWindowHelper.showFromTop(view);


从底部弹出显示

[code]popupWindowHelper.showFromBottom(v);


另外还保留的原生的popupwindow方法

设置是否要在弹出外区域点击关闭弹窗(默认是true)

[code]/**
     * touch outside dismiss the popupwindow, default is ture
     * @param isCancelable
     */
    public void setCancelable(boolean isCancelable) {
        this.isCancelable = isCancelable;
    }


源码分析

首先,showAsDropDown是原生的方法,没什么好说的,至于showAsPopUp的方法(在按钮的上面弹出窗口),请看代码

[code]public void showAsPopUp(View anchor) {
        showAsPopUp(anchor, 0, 0);
    }

    public void showAsPopUp(View anchor, int xoff, int yoff) {
        initPopupWindow(TYPE_WRAP_CONTENT);
        mPopupWindow.setAnimationStyle(R.style.AnimationUpPopup);
        popupView.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        int height = popupView.getMeasuredHeight();
        int[] location = new int[2];
        anchor.getLocationInWindow(location);
        mPopupWindow.showAtLocation(anchor, Gravity.LEFT | Gravity.TOP, location[0] + xoff, location[1] - height + yoff);
    }


先初始化popupwindow,然后通过setAnimationStyle设置动画效果,接着用measure测量该View的高度,最后显示还是用showAtLocation的方法显示

从顶部弹出和从底部弹出,也用的是类似的方法,不够在初始化的时候,width使用的是Match_parent的属性,另外动画效果也做了对应的修改,代码很简单,请看

[code]public void showFromBottom(View anchor) {
        initPopupWindow(TYPE_MATCH_PARENT);
        mPopupWindow.setAnimationStyle(R.style.AnimationFromButtom);
        mPopupWindow.showAtLocation(anchor, Gravity.LEFT | Gravity.BOTTOM, 0, 0);
    }

    public void showFromTop(View anchor) {
        initPopupWindow(TYPE_MATCH_PARENT);
        mPopupWindow.setAnimationStyle(R.style.AnimationFromTop);
        mPopupWindow.showAtLocation(anchor, Gravity.LEFT | Gravity.TOP, 0, getStatusBarHeight());
    }


写这个库的时候,一般想的是尽量用最简单的方法实现,代码量也很少,且使用起来也很方便,如有什么问题,欢迎指正

项目源码请点击这里

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: