Android layout和onLayout区别

Android生命周期流程图

  1. 使用者不同:layout是子类确定自己位置的方法,使用者为子类;onLayout是父类确定子类位置的方法,使用者为父类。
  2. 调用者不同:layout是在onMeasure方法之后,由父类调用执行;onLayout方法是在onSizeChanged方法之后,layout中判断size变化时调用。
  3. 使用习惯不同:一般layout方法不需要重写;而onLayout方法一般都需要重写。

举例子:

布局:

	<yang.shuai.ysandroid.TestView
        android:id="@+id/testView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent">
        <View
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/red"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/back_ground"/>
	yang.shuai.ysandroid.TestView>

ViewGroup onLayout写法:

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        Log.w("测试","onLayout");
        for(int i = 0;i<getChildCount();i++){
            View view = getChildAt(i);
            view.layout(left,top,left+100,top+100);
            left += 100+20;
        }
    }

效果:
Android layout和onLayout区别_第1张图片

你可能感兴趣的:(自定义view)