Android自定义View——从零开始实现可展开收起的水平菜单栏

版权声明:本文为博主原创文章,未经博主允许不得转载。
系列教程:Android开发之从零开始系列
源码:github.com/AnliaLee/ExpandMenu,欢迎star

大家要是看到有错误的地方或者有啥好的建议,欢迎留言评论

前言:最近项目里要实现一个 可展开收起的水平菜单栏控件,刚接到需求时想着用自定义View自己来绘制,发现要实现 圆角、阴影、菜单滑动等效果非常复杂且耗时间。好在这些效果 Android原生代码中都已经有非常成熟的解决方案,我们只需要去继承它们进行 二次开发就行。本期将教大家如何继承 ViewGroup(RelativeLayout)实现自定义菜单栏

本篇只着重于思路和实现步骤,里面用到的一些知识原理不会非常细地拿来讲,如果有不清楚的api或方法可以在网上搜下相应的资料,肯定有大神讲得非常清楚的,我这就不献丑了。本着认真负责的精神我会把相关知识的博文链接也贴出来(其实就是懒不想写那么多哈哈),大家可以自行传送。为了照顾第一次阅读系列博客的小伙伴,本篇会出现一些在之前系列博客就讲过的内容,看过的童鞋自行跳过该段即可

国际惯例,先上效果图

Android自定义View——从零开始实现可展开收起的水平菜单栏_第1张图片
目录
  • 为菜单栏设置背景
  • 绘制菜单栏按钮
  • 设置按钮动画与点击事件
  • 设置菜单展开收起动画
  • 测量菜单栏子View的位置

为菜单栏设置背景

自定义ViewGroup自定义View的绘制过程有所不同,View可以直接在自己的onDraw方法中绘制所需要的效果,而ViewGroup会先测量子View的大小位置(onLayout),然后再进行绘制,如果子View或background为空,则不会调用draw方法绘制。当然我们可以调用setWillNotDraw(false)ViewGroup可以在子View或background为空的情况下进行绘制,但我们会为ViewGroup设置一个默认背景,所以可以省去这句代码

设置背景很简单,因为要实现圆角、描边等效果,所以我们选择使用GradientDrawable来定制背景,然后调用setBackground方法设置背景。创建HorizontalExpandMenu,继承自RelativeLayout,同时自定义Attrs属性

public class HorizontalExpandMenu extends RelativeLayout {
    private Context mContext;
    private AttributeSet mAttrs;

    private int defaultWidth;//默认宽度
    private int defaultHeight;//默认长度
    private int viewWidth;
    private int viewHeight;

    private int menuBackColor;//菜单栏背景色
    private float menuStrokeSize;//菜单栏边框线的size
    private int menuStrokeColor;//菜单栏边框线的颜色
    private float menuCornerRadius;//菜单栏圆角半径

    public HorizontalExpandMenu(Context context) {
        super(context);
        this.mContext = context;
        init();
    }

    public HorizontalExpandMenu(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        this.mAttrs = attrs;
        init();
    }

    private void init(){
        TypedArray typedArray = mContext.obtainStyledAttributes(mAttrs, R.styleable.HorizontalExpandMenu);

        defaultWidth = DpOrPxUtils.dip2px(mContext,200);
        defaultHeight = DpOrPxUtils.dip2px(mContext,40);

        menuBackColor = typedArray.getColor(R.styleable.HorizontalExpandMenu_back_color,Color.WHITE);
        menuStrokeSize = typedArray.getDimension(R.styleable.HorizontalExpandMenu_stroke_size,1);
        menuStrokeColor = typedArray.getColor(R.styleable.HorizontalExpandMenu_stroke_color,Color.GRAY);
        menuCornerRadius = typedArray.getDimension(R.styleable.HorizontalExpandMenu_corner_radius,DpOrPxUtils.dip2px(mContext,20));
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = measureSize(defaultHeight, heightMeasureSpec);
        int width = measureSize(defaultWidth, widthMeasureSpec);
        viewHeight = height;
        viewWidth = width;
        setMeasuredDimension(viewWidth,viewHeight);

        //布局代码中如果没有设置background属性则在此处添加一个背景
        if(getBackground()==null){
            setMenuBackground();
        }
    }

    private int measureSize(int defaultSize, int measureSpec) {
        int result = defaultSize;
        int specMode = View.MeasureSpec.getMode(measureSpec);
        int specSize = View.MeasureSpec.getSize(measureSpec);

        if (specMode == View.MeasureSpec.EXACTLY) {
            result = specSize;
        } else if (specMode == View.MeasureSpec.AT_MOST) {
            result = Math.min(result, specSize);
        }
        return result;
    }

    /**
     * 设置菜单背景,如果要显示阴影,需在onLayout之前调用
     */
    private void setMenuBackground(){
        GradientDrawable gd = new GradientDrawable();
        gd.setColor(menuBackColor);
        gd.setStroke((int)menuStrokeSize, menuStrokeColor);
        gd.setCornerRadius(menuCornerRadius);
        setBackground(gd);
    }
}

attrs属性



    
    
        
        
        
        
    

在布局文件中使用



效果如图


绘制菜单栏按钮

我们要绘制菜单栏两边的按钮,首先是要为按钮“圈地”(测量位置和大小)。设置按钮区域为正方形,位于左侧或右侧(根据开发者设置而定)边长和菜单栏ViewGroup的高相等。按钮中的加号可以使用Path进行绘制(当然也可以用矢量图位图),代码如下

public class HorizontalExpandMenu extends RelativeLayout {
    //省略部分代码...
    private float buttonIconDegrees;//按钮icon符号竖线的旋转角度
    private float buttonIconSize;//按钮icon符号的大小
    private float buttonIconStrokeWidth;//按钮icon符号的粗细
    private int buttonIconColor;//按钮icon颜色

    private int buttonStyle;//按钮类型
    private int buttonRadius;//按钮矩形区域内圆半径
    private float buttonTop;//按钮矩形区域top值
    private float buttonBottom;//按钮矩形区域bottom值

    private Point rightButtonCenter;//右按钮中点
    private float rightButtonLeft;//右按钮矩形区域left值
    private float rightButtonRight;//右按钮矩形区域right值

    private Point leftButtonCenter;//左按钮中点
    private float leftButtonLeft;//左按钮矩形区域left值
    private float leftButtonRight;//左按钮矩形区域right值

    /**
     * 根按钮所在位置,默认为右边
     */
    public class ButtonStyle {
        public static final int Right = 0;
        public static final int Left = 1;
    }

    private void init(){
        //省略部分代码...
        buttonStyle = typedArray.getInteger(R.styleable.HorizontalExpandMenu_button_style,ButtonStyle.Right);
        buttonIconDegrees = 0;
        buttonIconSize = typedArray.getDimension(R.styleable.HorizontalExpandMenu_button_icon_size,DpOrPxUtils.dip2px(mContext,8));
        buttonIconStrokeWidth = typedArray.getDimension(R.styleable.HorizontalExpandMenu_button_icon_stroke_width,8);
        buttonIconColor = typedArray.getColor(R.styleable.HorizontalExpandMenu_button_icon_color,Color.GRAY);

        buttonIconPaint = new Paint();
        buttonIconPaint.setColor(buttonIconColor);
        buttonIconPaint.setStyle(Paint.Style.STROKE);
        buttonIconPaint.setStrokeWidth(buttonIconStrokeWidth);
        buttonIconPaint.setAntiAlias(true);

        path = new Path();
        leftButtonCenter = new Point();
        rightButtonCenter = new Point();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = measureSize(defaultHeight, heightMeasureSpec);
        int width = measureSize(defaultWidth, widthMeasureSpec);
        viewHeight = height;
        viewWidth = width;
        setMeasuredDimension(viewWidth,viewHeight);

        buttonRadius = viewHeight/2;
        layoutRootButton();

        //布局代码中如果没有设置background属性则在此处添加一个背景
        if(getBackground()==null){
            setMenuBackground();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        layoutRootButton();
        if(buttonStyle == ButtonStyle.Right){
            drawRightIcon(canvas);
        }else {
            drawLeftIcon(canvas);
        }

        super.onDraw(canvas);//注意父方法在最后调用,以免icon被遮盖
    }

    /**
     * 测量按钮中点和矩形位置
     */
    private void layoutRootButton(){
        buttonTop = 0;
        buttonBottom = viewHeight;

        rightButtonCenter.x = viewWidth- buttonRadius;
        rightButtonCenter.y = viewHeight/2;
        rightButtonLeft = rightButtonCenter.x- buttonRadius;
        rightButtonRight = rightButtonCenter.x+ buttonRadius;

        leftButtonCenter.x = buttonRadius;
        leftButtonCenter.y = viewHeight/2;
        leftButtonLeft = leftButtonCenter.x- buttonRadius;
        leftButtonRight = leftButtonCenter.x+ buttonRadius;
    }

    /**
     * 绘制左边的按钮
     * @param canvas
     */
    private void drawLeftIcon(Canvas canvas){
        path.reset();
        path.moveTo(leftButtonCenter.x- buttonIconSize, leftButtonCenter.y);
        path.lineTo(leftButtonCenter.x+ buttonIconSize, leftButtonCenter.y);
        canvas.drawPath(path, buttonIconPaint);//划横线

        canvas.save();
        canvas.rotate(-buttonIconDegrees, leftButtonCenter.x, leftButtonCenter.y);//旋转画布,让竖线可以随角度旋转
        path.reset();
        path.moveTo(leftButtonCenter.x, leftButtonCenter.y- buttonIconSize);
        path.lineTo(leftButtonCenter.x, leftButtonCenter.y+ buttonIconSize);
        canvas.drawPath(path, buttonIconPaint);//画竖线
        canvas.restore();
    }

    /**
     * 绘制右边的按钮
     * @param canvas
     */
    private void drawRightIcon(Canvas canvas){
        path.reset();
        path.moveTo(rightButtonCenter.x- buttonIconSize, rightButtonCenter.y);
        path.lineTo(rightButtonCenter.x+ buttonIconSize, rightButtonCenter.y);
        canvas.drawPath(path, buttonIconPaint);//划横线

        canvas.save();
        canvas.rotate(buttonIconDegrees, rightButtonCenter.x, rightButtonCenter.y);//旋转画布,让竖线可以随角度旋转
        path.reset();
        path.moveTo(rightButtonCenter.x, rightButtonCenter.y- buttonIconSize);
        path.lineTo(rightButtonCenter.x, rightButtonCenter.y+ buttonIconSize);
        canvas.drawPath(path, buttonIconPaint);//画竖线
        canvas.restore();
    }
}

新增attrs属性


    //省略部分代码...
    
        
        
    
    
    
    

布局文件



    
        
        
        
        
    

效果如图


设置按钮动画与点击事件

之前我们定义了buttonIconDegrees属性,下面我们通过Animation的插值器增减buttonIconDegrees的数值让按钮符号可以进行变换,同时监听Touch为按钮设置点击事件

public class HorizontalExpandMenu extends RelativeLayout {
    //省略部分代码...
    private boolean isExpand;//菜单是否展开,默认为展开
    private float downX = -1;
    private float downY = -1;
    private int expandAnimTime;//展开收起菜单的动画时间

    private void init(){
        //省略部分代码...
        buttonIconDegrees = 90;//菜单初始状态为展开,所以旋转角度为90,按钮符号为 - 号
        expandAnimTime = typedArray.getInteger(R.styleable.HorizontalExpandMenu_expand_time,400);
        isExpand = true;
        anim = new ExpandMenuAnim();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        float x = event.getX();
        float y = event.getY();
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                downX = event.getX();
                downY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                switch (buttonStyle){
                    case ButtonStyle.Right:
                        if(x==downX&&y==downY&&y>=buttonTop&&y<=buttonBottom&&x>=rightButtonLeft&&x<=rightButtonRight){
                            expandMenu(expandAnimTime);
                        }
                        break;
                    case ButtonStyle.Left:
                        if(x==downX&&y==downY&&y>=buttonTop&&y<=buttonBottom&&x>=leftButtonLeft&&x<=leftButtonRight){
                            expandMenu(expandAnimTime);
                        }
                        break;
                }
                break;
        }
        return true;
    }

    private class ExpandMenuAnim extends Animation {
        public ExpandMenuAnim() {}

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            if(isExpand){//展开菜单
                buttonIconDegrees = 90 * interpolatedTime;
            }else {//收起菜单
                buttonIconDegrees = 90 - 90 * interpolatedTime;
            }
            postInvalidate();
        }
    }

    /**
     * 展开收起菜单
     * @param time 动画时间
     */
    private void expandMenu(int time){
        anim.setDuration(time);
        isExpand = isExpand ?false:true;
        this.startAnimation(anim);
    }
}

效果如图

Android自定义View——从零开始实现可展开收起的水平菜单栏_第2张图片

设置菜单展开收起动画

ViewGroup的大小和位置需要用到layout()方法进行设置,和按钮动画一样,我们使用动画插值器动态改变菜单的长度

public class HorizontalExpandMenu extends RelativeLayout {
    //省略部分代码...
    private float backPathWidth;//绘制子View区域宽度
    private float maxBackPathWidth;//绘制子View区域最大宽度
    private int menuLeft;//menu区域left值
    private int menuRight;//menu区域right值

    private boolean isFirstLayout;//是否第一次测量位置,主要用于初始化menuLeft和menuRight的值

    private void init(){
        //省略部分代码...
        isFirstLayout = true;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //省略部分代码...
        maxBackPathWidth = viewWidth- buttonRadius *2;
        backPathWidth = maxBackPathWidth;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        //如果子View数量为0时,onLayout后getLeft()和getRight()才能获取相应数值,menuLeft和menuRight保存menu初始的left和right值
        if(isFirstLayout){
            menuLeft = getLeft();
            menuRight = getRight();
            isFirstLayout = false;
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        viewWidth = w;//当menu的宽度改变时,重新给viewWidth赋值
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //省略部分代码...
        switch (event.getAction()){
            case MotionEvent.ACTION_UP:
                if(backPathWidth==maxBackPathWidth || backPathWidth==0){//动画结束时按钮才生效
                    switch (buttonStyle){
                        case ButtonStyle.Right:
                            if(x==downX&&y==downY&&y>=buttonTop&&y<=buttonBottom&&x>=rightButtonLeft&&x<=rightButtonRight){
                                expandMenu(expandAnimTime);
                            }
                            break;
                        case ButtonStyle.Left:
                            if(x==downX&&y==downY&&y>=buttonTop&&y<=buttonBottom&&x>=leftButtonLeft&&x<=leftButtonRight){
                                expandMenu(expandAnimTime);
                            }
                            break;
                    }
                }
                break;
        }
    }

    private class ExpandMenuAnim extends Animation {
        public ExpandMenuAnim() {}

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            float left = menuRight - buttonRadius *2;//按钮在右边,菜单收起时按钮区域left值
            float right = menuLeft + buttonRadius *2;//按钮在左边,菜单收起时按钮区域right值

            if(isExpand){//打开菜单
                backPathWidth = maxBackPathWidth * interpolatedTime;
                buttonIconDegrees = 90 * interpolatedTime;
            }else {//关闭菜单
                backPathWidth = maxBackPathWidth - maxBackPathWidth * interpolatedTime;
                buttonIconDegrees = 90 - 90 * interpolatedTime;
            }
            if(buttonStyle == ButtonStyle.Right){
                layout((int)(left-backPathWidth),getTop(), menuRight,getBottom());//会调用onLayout重新测量子View位置
            }else {
                layout(menuLeft,getTop(),(int)(right+backPathWidth),getBottom());
            }
            postInvalidate();
        }
    }
}

效果如图

Android自定义View——从零开始实现可展开收起的水平菜单栏_第3张图片

测量菜单栏子View的位置

为了菜单栏的显示效果,我们限制其直接子View的数量为一个。在子View数量不为0的情况下,我们需要动态显示和隐藏子View,且在onLayout()方法中测量子View的位置,修改HorizontalExpandMenu

public class HorizontalExpandMenu extends RelativeLayout {
    //省略部分代码...
    private boolean isAnimEnd;//动画是否结束
    private View childView;

    private void init(){
        //省略部分代码...
        isAnimEnd = false;
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {}

            @Override
            public void onAnimationEnd(Animation animation) {
                isAnimEnd = true;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {}
        });
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        //如果子View数量为0时,onLayout后getLeft()和getRight()才能获取相应数值,menuLeft和menuRight保存menu初始的left和right值
        if(isFirstLayout){
            menuLeft = getLeft();
            menuRight = getRight();
            isFirstLayout = false;
        }
        if(getChildCount()>0){
            childView = getChildAt(0);
            if(isExpand){
                if(buttonStyle == Right){
                    childView.layout(leftButtonCenter.x,(int) buttonTop,(int) rightButtonLeft,(int) buttonBottom);
                }else {
                    childView.layout((int)(leftButtonRight),(int) buttonTop,rightButtonCenter.x,(int) buttonBottom);
                }

                //限制子View在菜单内,LayoutParam类型和当前ViewGroup一致
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(viewWidth,viewHeight);
                layoutParams.setMargins(0,0,buttonRadius *3,0);
                childView.setLayoutParams(layoutParams);
            }else {
                childView.setVisibility(GONE);
            }
        }
        if(getChildCount()>1){//限制直接子View的数量
            throw new IllegalStateException("HorizontalExpandMenu can host only one direct child");
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        viewWidth = w;//当menu的宽度改变时,重新给viewWidth赋值
        if(isAnimEnd){//防止出现动画结束后菜单栏位置大小测量错误的bug
            if(buttonStyle == Right){
                if(!isExpand){
                    layout((int)(menuRight - buttonRadius *2-backPathWidth),getTop(), menuRight,getBottom());
                }
            }else {
                if(!isExpand){
                    layout(menuLeft,getTop(),(int)(menuLeft + buttonRadius *2+backPathWidth),getBottom());
                }
            }
        }
    }

    private class ExpandMenuAnim extends Animation {
        public ExpandMenuAnim() {}

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            float left = menuRight - buttonRadius *2;//按钮在右边,菜单收起时按钮区域left值
            float right = menuLeft + buttonRadius *2;//按钮在左边,菜单收起时按钮区域right值
            if(childView!=null) {
                childView.setVisibility(GONE);
            }
            if(isExpand){//打开菜单
                backPathWidth = maxBackPathWidth * interpolatedTime;
                buttonIconDegrees = 90 * interpolatedTime;

                if(backPathWidth==maxBackPathWidth){
                    if(childView!=null) {
                        childView.setVisibility(VISIBLE);
                    }
                }
            }else {//关闭菜单
                backPathWidth = maxBackPathWidth - maxBackPathWidth * interpolatedTime;
                buttonIconDegrees = 90 - 90 * interpolatedTime;
            }
            if(buttonStyle == Right){
                layout((int)(left-backPathWidth),getTop(), menuRight,getBottom());//会调用onLayout重新测量子View位置
            }else {
                layout(menuLeft,getTop(),(int)(right+backPathWidth),getBottom());
            }
            postInvalidate();
        }
    }

    /**
     * 展开收起菜单
     * @param time 动画时间
     */
    private void expandMenu(int time){
        anim.setDuration(time);
        isExpand = isExpand ?false:true;
        this.startAnimation(anim);
        isAnimEnd = false;
    }
}

布局代码


    
        
            
            
            
            
        
    
    
        
            
                
                
                
                
            
        
    

效果如图

Android自定义View——从零开始实现可展开收起的水平菜单栏_第4张图片

至此本篇教程到此结束,如果大家看了感觉还不错麻烦点个赞,你们的支持是我最大的动力~


你可能感兴趣的:(Android自定义View——从零开始实现可展开收起的水平菜单栏)