Android自定义布局:ViewGroup

本文探讨了Android中View的工作流程,并重点讲解如何自定义ViewGroup,包括实现wrap_content属性和管理子View的功能,帮助理解并创建自定义布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前面的文章介绍了自定义View,自定义View中重写了ondraw()函数,绘制我们需要的图形,重写了onMeasure函数,实现View的wrap_content属性,完成了View的测量。ViewGroup是对View进行管理的布局,例如LinearLayout和Framelayout等等,本文主要介绍自定义ViewGroup的实现。


View的工作流程

View的工作流程主要是指measure、layout、draw这三个流程,即测量、布局和绘制。其中measure确定View测量的宽高,layout确定最终的宽高以及view四个顶点的位置,draw将view绘制到屏幕。

View的measure过程相对简单,在measure方法中调用View的onMeasure方法,onMeasure方法根据不同的测量模式(UNSPECIFIED、AT_MOST、EXACTLY)设置相应的测量大小。直接继承View的自定义控件需要重写onMeasure方法并设置wrap_content时的大小,否则在布局中使用wrap_content就相当于使用match_parent。
ViewGroup的测量过程除了要完成自己的测量,还要测量所有的子元素大小,ViewGroup提供了一个measureChildren的方法,对每一个子元素进行递归测量。

Layout是ViewGroup用来确定子元素的位置,ViewGroup的位置确定后,在onLayout方法中会遍历所有的子元素并调用其layout方法,layout方法中onLayout方法又会被调用。

View的绘制过程比较简单,作用是将View绘制到屏幕上,绘制过程遵循以下几步

1.绘制背景backgroud.draw(canvas)。
2.绘制自己(onDraw)
3.绘制children(dispatchDraw)。
4.绘制装饰(onDrawScrollBars)


自定义ViewGroup

这个例子中我们定义一种垂直方向的线性布局,主要说明onMeasure和onLayout的写法
首先新建mViewGroup继承ViewGroup,重写onMeasure方法:
@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec,heightMeasureSpec);
        measureChildren(widthMeasureSpec,heightMeasureSpec);
    }
onMeasure方法直接调用了父类的测量方法,然后测量所有的子控件,为了简单没有考虑wrap_content的情况。

重写onLayout方法:
@Override
    protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
        int height = 0;
        int count =  getChildCount();
        View child;
        for(int k=0;k<count;k++){
            child = getChildAt(k);
            child.layout(0,height,child.getMeasuredWidth(),height+child.getMeasuredHeight());
            height += child.getMeasuredHeight();
        }
    }

Layout是确定子元素位置的,我们要实验垂直布局,每个子view的宽度即为水平布局的位置,而垂直位置需要根据上一个子view的高度决定,首先定义高度hight为0,一次设置每个子view的top和button。

xml中的布局如下:

<my.project.test.mViewGroup
        android:layout_height="match_parent"
        android:layout_width="match_parent">
        <Button
            android:text="1"
            android:layout_width="60dp"
            android:layout_height="80dp" />
        <Button
            android:text="2"
            android:layout_width="50dp"
            android:layout_height="80dp" />
        <Button
            android:text="3"
            android:layout_width="50dp"
            android:layout_height="80dp" />
        <Button
            android:text="4"
            android:layout_width="50dp"
            android:layout_height="80dp" />
    </my.project.test.mViewGroup>

效果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值