自定义View二篇,如何自定义一个规范的ViewGroup

简介: 自定义View二篇,如何自定义一个规范的ViewGroup

前言

在自定义View开篇,必须跨过的一道坎儿 中,我们介绍了自定义View的几种方式,以及如何实现一个规范的自定义View,上文中也说了,实现一个规范的自定义ViewGroup是一件比较困难的事情,因为要考虑的情况包含 本身的padding以及子view的margin 与 本身wrap_content 问题。

image.gif

如何实现一个规范的ViewGroup,以实现垂直布局的LinerLayout为例

    • 新建LinerLayoutView 继承自ViewGroup

    首先我们让LinerLayoutView 适应wrap_content的情况,在onMeasure中处理如下,同自定义View处理一样,不同的是我们需要计算子View宽高,代码如下所示:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
        int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        measureChildren(widthMeasureSpec,heightMeasureSpec);
        int totalheight = 0;
        int totalWidth = 0;
        for (int i = 0; i < getChildCount(); i++){
            View childView = getChildAt(i);
            int childrWidth = childView.getMeasuredWidth();
            int childHeight = childView.getMeasuredHeight();
            totalheight = totalheight + childHeight;
            totalWidth = Math.max(totalWidth,childrWidth);
        }
        if (heightMode == MeasureSpec.AT_MOST && widthMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(totalWidth,totalheight);
        }else if (heightMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(measureWidth,totalheight);
        }else if (widthMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(totalWidth,measureHeight);
        }
    }

    image.gif

    我们需要调用下面方法来测量子view

    measureChildren(widthMeasureSpec,heightMeasureSpec);

    image.gif

    因为这里我们是垂直排列的,所以要循环计算view的总高度,wrap_content情况对应的宽度为子View最大的宽度,上面代码比较简单 我们主要来看onLayout方法。

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int totalHeight = 0;
        for (int i = 0; i < getChildCount(); i++){
            View childView = getChildAt(i);
            int childrWidth = childView.getMeasuredWidth();
            int childHeight = childView.getMeasuredHeight();
            childView.layout(0,totalHeight,childrWidth,totalHeight + childHeight);
            totalHeight = totalHeight + childHeight;
        }
    }

    image.gif

    view.layout方法 是将view放置在什么地方,分别对应left、top、right、bottom四个点,这里我们需要注意的是,务必使用getMeasureWidth不能使用getWidth,因为前者是在测量的时候获取的,后者在布局完成之后才能获取到。

    在布局文件中 引用这个ViewGroup,并且添加两个子View,代码如下所示:

    <com.support.hlq.layout.LinerLayoutView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimaryDark">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="kkko"
            android:textColor="@color/colorAccent" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="kkko"
            android:textColor="@color/colorAccent" />
    </com.support.hlq.layout.LinerLayoutView>

    image.gif

    运行结果如图所示,可以看到我们已经适配了wrap_content的情况

    image.gif

    考虑ViewGroup的padding问题

    上面代码,已经实现了最简单的垂直排列,我们给LinerLayoutView设置大小为40的边距,发现边距并没有生效,所以我们需要在onMeasure以及onLayout的方法中考虑padding问题。改写onMeasure方法如下:

    for (int i = 0; i < getChildCount(); i++){
        View childView = getChildAt(i);
        int childrWidth = childView.getMeasuredWidth();
        int childHeight = childView.getMeasuredHeight();
        totalheight = totalheight + childHeight;
        totalWidth = Math.max(totalWidth,childrWidth);
    }
    totalheight = totalheight + getPaddingTop() + getPaddingBottom();
    totalWidth = totalWidth + getPaddingLeft() + getPaddingRight();

    image.gif

    因为我们处理的是ViewGroup的边距,所以我们只需要对最终计算的高度和宽度分别加上上下边距 和左右边距即可,这里你可能会有疑问

    int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
    int measureHeight = MeasureSpec.getSize(heightMeasureSpec);

    image.gif

    为什么上面两处代码不需要加上边距呢,因为MeasureSpec获取到的大小是已经包含过padding,所以我们不需要处理通过MeasureSpec获取的宽高。

    接下来,我们修改layout方法

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int totalHeight = getPaddingTop();
        for (int i = 0; i < getChildCount(); i++){
            View childView = getChildAt(i);
            int childrWidth = childView.getMeasuredWidth();
            int childHeight = childView.getMeasuredHeight();
            childView.layout(0 + getPaddingLeft(),
                    totalHeight,
                    childrWidth + getPaddingLeft(),
                    totalHeight + childHeight + getPaddingTop());
            totalHeight = totalHeight + childHeight;
        }
    }

    image.gif

    left点我们加上getPaddingLeft,总高度由0修改为getPaddingTop,其他两点也分别加上边距布局即可,运行结果如下所示

    image.gif

    我们可以看出ViewGroup的边距已经生效了。

    考虑子View的Margin问题

    到这里 这个自定义的ViewGroup还是不够规范,不信我们来给第一个TextView设置下边距为20dp

    <com.support.hlq.layout.LinerLayoutView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimaryDark">
        <TextView
            android:layout_marginBottom="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="kkko"
            android:textColor="@color/colorAccent" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="kkko"
            android:textColor="@color/colorAccent" />
    </com.support.hlq.layout.LinerLayoutView>

    image.gif

    在这里,因为要获取到margin所以必须重写

    generateLayoutParams 方法和 generateDefaultLayoutParams 方法

    image.gif

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }
    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new MarginLayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
    }
    @Override
    protected LayoutParams generateLayoutParams(LayoutParams p) {
        return new MarginLayoutParams(p);
    }

    image.gif

    重写上面三个方法后,我们才能获取margin参数,同样的我们首先在onMeasure中考虑子view边距

    for (int i = 0; i < getChildCount(); i++) {
        View childView = getChildAt(i);
        MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
        int childrWidth = childView.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
        int childHeight = childView.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
        totalheight = totalheight + childHeight;
        totalWidth = Math.max(totalWidth, childrWidth);
    }

    image.gif

    还要在获取宽高的时候加上对应的边距即可,同样还需要在onLayout方法中考虑子view 的边距问题,修改如下:

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int totalHeight = getPaddingTop();
        for (int i = 0; i < getChildCount(); i++) {
            View childView = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
            int childrWidth = childView.getMeasuredWidth() ;
            int childHeight = childView.getMeasuredHeight() ;
            childView.layout(getPaddingLeft() + lp.leftMargin,
                    totalHeight + lp.topMargin,
                    childrWidth + getPaddingLeft() + lp.leftMargin,
                    totalHeight + childHeight + getPaddingTop() + lp.topMargin);
            totalHeight = totalHeight + childHeight + lp.topMargin + lp.bottomMargin;
        }
    }

    image.gif

    在layout的时候考虑子view的边距,记得在计算总高度的时候 也要加上边距和下边距,运行结果如下图所示

    image.gif

    这样一来,我们就定义了一个比较规范的ViewGroup,加上我们上篇文章讲的自定义属性,相信大家都掌握了自定义View的方法了。

    目录
    相关文章
    |
    2月前
    |
    存储 Android开发 开发者
    Android项目架构设计问题之定义RecyclerView的ViewHolder如何解决
    Android项目架构设计问题之定义RecyclerView的ViewHolder如何解决
    32 0
    |
    5月前
    |
    前端开发 Android开发 容器
    自定义View之View的工作原理
    自定义View之View的工作原理
    44 0
    |
    XML Android开发 数据格式
    Android自定义控件(十二)——自定义属性及应用
    Android自定义控件(十二)——自定义属性及应用
    167 0
    Android自定义控件(十二)——自定义属性及应用
    |
    前端开发 Android开发
    Android 开发进阶: 自定义 View 1-1 绘制基础
    Android 开发进阶: 自定义 View 1-1 绘制基础
    122 0
    |
    XML 前端开发 Android开发
    自定义View - 简单的TextView封装
    引言 在平常的开发中,我们总会有各种各样的按钮,圆角的、直角的、正常状态的、按下状态的、禁用状态的。一直的做法就是在drawable中写一个selector,然后用item加shap来实现。
    1178 0
    |
    程序员 Android开发
    有关自定义View的学习(View的点击事件传递流程)
    1、安卓OnTouchListener,onTouchEvent,onClickListener执行顺序 首先我们相对比较熟悉的是处理滑动冲突时候的三个事件(ViewGroup 继承 View) (View是没有onInterceptTouchEvent方法的),先看看ViewGroup和View的事件流程方法: ViewGroup 1.
    1174 0
    |
    Android开发
    android之View Touch事件的传递流程
    android应用界面的布局如下图所示,一般我们在展示一个界面时会使用一个Activity表示;而Activity时通过Window展示的,android的Window实现类叫PhoneWindow;PhoneWindow类有个mDecor的DectorView全局变量,用来对界面的View元素进行修饰;DectorView用来修饰ActionBar、ContentView(Activity.setContentView);ContentView里面包含了用户自定义的一些子Layout。
    1198 0