Android onLayout父级子级调用顺序

概述

在Android开发中,onLayout方法是ViewGroup中的一个重要方法,用于确定子View的布局位置。本文将详细介绍onLayout方法的调用顺序以及每一步需要做的事情。

调用顺序表格

下表显示了父级和子级调用onLayout方法的顺序:

步骤 父级调用onLayout 子级调用onLayout
1 onMeasure onMeasure
2 onMeasure onLayout
3 onLayout onMeasure
4 onLayout onLayout

步骤详解

步骤1:父级调用onMeasure方法

在父级ViewGroup的onMeasure方法中,会调用子View的measure方法,以确定子View的尺寸。示例代码如下:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    // 调用子View的measure方法
    for (int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);
        measureChild(child, widthMeasureSpec, heightMeasureSpec);
    }
}

此步骤的主要目的是测量子View的尺寸。

步骤2:父级调用onLayout方法

在父级ViewGroup的onLayout方法中,会通过调用子View的layout方法来确定子View的位置。示例代码如下:

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    // 确定子View的位置
    for (int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);
        child.layout(left, top, right, bottom);
    }
}

此步骤的主要目的是确定子View的位置。

步骤3:子级调用onMeasure方法

在子View的onMeasure方法中,会根据父级传递的测量规格来测量自身的尺寸,并通过setMeasuredDimension方法来保存测量结果。示例代码如下:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    // 测量自身的尺寸
    int measuredWidth = measureWidth(widthMeasureSpec);
    int measuredHeight = measureHeight(heightMeasureSpec);
    setMeasuredDimension(measuredWidth, measuredHeight);
}

此步骤的主要目的是测量自身的尺寸。

步骤4:子级调用onLayout方法

在子View的onLayout方法中,会通过调用layout方法来确定自身的位置。示例代码如下:

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    // 确定自身的位置
    layout(left, top, right, bottom);
}

此步骤的主要目的是确定自身的位置。

总结

通过以上步骤的详解,我们可以清楚地了解到android onLayout父级子级调用顺序。首先,在父级调用onMeasure方法时,会调用子View的measure方法来测量子View的尺寸;然后,在父级调用onLayout方法时,会通过调用子View的layout方法来确定子View的位置;接着,子级调用onMeasure方法时,会测量自身的尺寸,并保存测量结果;最后,子级调用onLayout方法时,会通过调用layout方法来确定自身的位置。

通过以上步骤的执行顺序,我们可以在自定义ViewGroup中正确地处理子View的布局。希望本文对于刚入行的小白能够有所帮助。

参考文献:

  • [Android Developers - onLayout](
  • [Android Developers - onMeasure](