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>

显示样式


image.png

2.layout()方法

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 我一直不明白,儿子对演相声的热衷究竟出于什么心理,为给别人带来欢笑?自己喜欢轻松搞笑的氛围?为了满足一种表现欲?我...
    飞花似梦8阅读 800评论 2 8
  •   对于前端开发者来说,要处理这个问题,必须先补充一个知识点,就是设备的 物理像素[设备像素] & 逻辑像素[CS...
    果汁凉茶丶阅读 30,903评论 4 60
  • 进行即兴演说需要多方面的知识素养,又需要敏捷的思维能力、快速的语言表达能力和应变能力。 1、知识素养准备 演讲者的...
    飞生阅读 670评论 0 4