自定義ViewGroup的知識(shí)點(diǎn)總結(jié)-持續(xù)更新
1、child.getMeasuredWidth()中會(huì)包含child的padding值
child的margin的值需要自行適配澜掩。
2市咽、在onMeasure方法中:
需要先對(duì)child進(jìn)行measure沸停,然后才能獲取到measuredWidth和measureHeight。
常用的測(cè)量方法有兩個(gè):
①ViewGroup#measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec)
但是measureChildWithMargins有個(gè)缺陷,它內(nèi)部的MarginLayoutParams是類(lèi)型強(qiáng)轉(zhuǎn)而來(lái)的浸颓,沒(méi)有添加非空判斷和類(lèi)型判斷,如果我們是自定義ViewGroup,這里會(huì)就有可能導(dǎo)致空指針和類(lèi)型轉(zhuǎn)換異常猾愿,為了解決這個(gè)問(wèn)題鹦聪,我自定義了一個(gè)方法,具體請(qǐng)看下面的measureChildWithMarginsAndUsedSpace
方法蒂秘。
3泽本、測(cè)量child時(shí),考慮到measureChildWithMargins的缺陷姻僧,這里自行實(shí)現(xiàn)了一個(gè)方法:measureChildWithMarginsAndUsedSpace
protected void measureChildWithMarginsAndUsedSpace(View child,
int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
// 兜底规丽,不會(huì)發(fā)生
if (child.getLayoutParams() == null) {
return;
}
final LayoutParams lp = child.getLayoutParams();
int paddingH = getPaddingLeft() + getPaddingRight() + widthUsed;
int paddingV = getPaddingTop() + getPaddingBottom() + heightUsed;
if (child.getLayoutParams() instanceof MarginLayoutParams) {
final MarginLayoutParams mlp = (MarginLayoutParams) child.getLayoutParams();
paddingH += mlp.leftMargin + mlp.rightMargin;
paddingV += mlp.topMargin + mlp.bottomMargin;
}
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, paddingH, lp.width);
final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, paddingV, lp.height);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
4、自定義ViewGroup時(shí)撇贺,必須考慮自身的padding赌莺,以及child的padding、margin等松嘶。
如果child也是自定義ViewGroup艘狭,那么也需要考慮因素。
5翠订、如何方便的支持child的margin數(shù)據(jù)?重寫(xiě)ViewGroup#generateLayoutParams方法即可
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}
ViewGroup只提供了ViewGroup.LayoutParams巢音,MarginLayoutParams是各個(gè)ViewGroup自行繼承實(shí)現(xiàn)的。
我們的ViewGroup要支持MarginLayoutParams最好的方式尽超,就是重寫(xiě)ViewGroup#generateLayoutParams方法官撼。
6、對(duì)于一些需要限制寬度的操作似谁,可以在onMeasure中操作傲绣。
先測(cè)量出實(shí)際寬度,如果超出了預(yù)期巩踏,再根據(jù)其最大長(zhǎng)度進(jìn)行二次測(cè)量即可秃诵。
常見(jiàn)的FlowLayout等自定義布局,都可以這么實(shí)現(xiàn)塞琼。
未完待續(xù)菠净,敬請(qǐng)期待。