自定义控件系列:
秒懂OnMeasure
秒懂OnLayout
让自定义ViewGroup里的子控件支持Margin
让自定义ViewGroup支持Padding
自定义ViewGroup的一个综合实践 FlowLayout
知识点
- 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自定义开发入门与实践》感谢大神的著作