秒懂OnLayout

自定义控件系列:
秒懂OnMeasure
秒懂OnLayout
让自定义ViewGroup里的子控件支持Margin
让自定义ViewGroup支持Padding
自定义ViewGroup的一个综合实践 FlowLayout

知识点

  1. onLayout方法就是按照自己的意愿,循环遍历所有的子控件,把每个子控件排列好

核心代码是通过child.layout(左,上,右,下)函数来设置子控件的位置。

应用

1. 接着上文完成MyLinearLayout (竖向的LinearLayout)

上文已经通过重写onMeasure支持了的AT_MOST模式,还差重写onLayout就完成自定义ViewGroup了

 @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int top = 0;
        int count = getChildCount();
        for (int i = 0; i < count; i++) {

            View child = getChildAt(i);

            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            // 布局,就是设置好这个子控件的左上右下
            child.layout(0, top, childWidth, top + childHeight);
            top += childHeight;

        }
        
    }

ok,预览一下:
在这里插入图片描述

参考:
《Android自定义开发入门与实践》感谢大神的著作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值