自定義控件系列:
秒懂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自定義開發入門與實踐》感謝大神的著作