自定义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的方法了。

    目录
    相关文章
    |
    Java
    java 一对多、多对多关系示例
    java 一对多、多对多关系示例
    423 0
    |
    Shell Android开发
    哪怕不学Gradle,这些开发中的常见操作,你也值得掌握(下)
    Gradle 是每个 Android 同学都逃不开的一个话题。
    284 0
    |
    Android开发
    TextView未绘制情况下获取其宽高
    /** * 注:StaticLayout是android中处理文字换行的一个类,TextView源码中也是通过这个类实现换行的,使用这个类可以 * 在不进行TextView绘制的前提下得到TextView的宽高,这里我们只需要获取到高度即可,这个高度当然也可以通过post * 在run中获取,但是这样做会有一个问题,界面是先绘制显示然后再计算高度根据我们的逻辑来收缩TextView的高度,在列表中 * 会出现闪烁的问题。
    2780 0
    |
    3天前
    |
    存储 关系型数据库 分布式数据库
    PostgreSQL 18 发布,快来 PolarDB 尝鲜!
    PostgreSQL 18 发布,PolarDB for PostgreSQL 全面兼容。新版本支持异步I/O、UUIDv7、虚拟生成列、逻辑复制增强及OAuth认证,显著提升性能与安全。PolarDB-PG 18 支持存算分离架构,融合海量弹性存储与极致计算性能,搭配丰富插件生态,为企业提供高效、稳定、灵活的云数据库解决方案,助力企业数字化转型如虎添翼!
    |
    14天前
    |
    弹性计算 关系型数据库 微服务
    基于 Docker 与 Kubernetes(K3s)的微服务:阿里云生产环境扩容实践
    在微服务架构中,如何实现“稳定扩容”与“成本可控”是企业面临的核心挑战。本文结合 Python FastAPI 微服务实战,详解如何基于阿里云基础设施,利用 Docker 封装服务、K3s 实现容器编排,构建生产级微服务架构。内容涵盖容器构建、集群部署、自动扩缩容、可观测性等关键环节,适配阿里云资源特性与服务生态,助力企业打造低成本、高可靠、易扩展的微服务解决方案。
    1304 5
    |
    13天前
    |
    机器学习/深度学习 人工智能 前端开发
    通义DeepResearch全面开源!同步分享可落地的高阶Agent构建方法论
    通义研究团队开源发布通义 DeepResearch —— 首个在性能上可与 OpenAI DeepResearch 相媲美、并在多项权威基准测试中取得领先表现的全开源 Web Agent。
    1331 87
    |
    2天前
    |
    弹性计算 安全 数据安全/隐私保护
    2025年阿里云域名备案流程(新手图文详细流程)
    本文图文详解阿里云账号注册、服务器租赁、域名购买及备案全流程,涵盖企业实名认证、信息模板创建、域名备案提交与管局审核等关键步骤,助您快速完成网站上线前的准备工作。
    184 82
    2025年阿里云域名备案流程(新手图文详细流程)