onLayout、layout方法分别代表什么

1.onLayout()方法

@Override
protected abstract void onLayout(boolean changed,int l, int t, int r, int b);

该方法在ViewGroup中定义是抽象函数,继承ViewGroup类的必须实现onLayout方法。onLayout传下来的l,t,r,b分别是放置父控件矩形边界的左上右下的坐标。

使用举例:

public class MyViewGroup extends ViewGroup{
    private int padding = 20;
    private int width = 200;

    public MyViewGroup(Context context) {
        super(context);
    }

    public MyViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onLayout(boolean boo, int l, int t, int r, int b) {
        View view;
        for (int j=0;j<getChildCount();j++){
            view = getChildAt(j);
            view.layout(l + padding,t + padding,l + width, t + width);
            l = padding + l + width;

            // l表示每个view的左边坐标,每个左边坐标会依次增大为自己的宽度+padding
        }
    }

}
布局:
   <com.example.apple.studydemo.MyViewGroup
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <View
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent"/>

        <View
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"/>

        <View
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#6d2"/>
    </com.example.apple.studydemo.MyViewGroup>

显示样式

《onLayout、layout方法分别代表什么》 image.png

2.layout()方法

public void layout(int l, int t, int r, int b);
View的放置方法,在View类实现。调用该方法需要传入放置View的矩形空间左上角left、top值和右下角right、bottom值。

    原文作者:奔跑吧李博
    原文地址: https://www.jianshu.com/p/7f319c1a6098
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞