開發(fā)中有時(shí)需要固定一個(gè)控件的寬高比, 有時(shí)候是View類型的,有時(shí)候是ViewGroup類型的,這兩者的實(shí)際實(shí)現(xiàn)是有一些區(qū)別的.
例如,有時(shí)候開發(fā)一個(gè)相冊(cè)界面,這種類型的

image.png
我們可以指定RecyclerView單個(gè)item的ImageView寬度為屏幕寬度的1/4,然后通過內(nèi)邊距來控制間隔,可以這樣來實(shí)現(xiàn)
public class SquareImageView extends ImageView {
//屏幕寬度
private int screenWidth;
private int ratio = 4;
// 省略...
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 保存測(cè)量結(jié)果即可, 指定寬高相等
setMeasuredDimension(screenWidth / ratio, screenWidth / ratio);
}
}
View類型的指定寬高比,基本上都是這樣來實(shí)現(xiàn)的,測(cè)量時(shí)保存自己想要的測(cè)量的結(jié)果即可
ViewGroup的實(shí)現(xiàn)方式上有所差別, ViewGroup可以包含childView, 不同于View, 還需要measureChild, 否則child的width,height就始終等于0,未被初始化
例如實(shí)現(xiàn)一個(gè)寬高比16:9的FrameLayout
public class RatioFrameLayout extends FrameLayout {
// 寬高比
private static final float RATIO = 16.f / 9;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 獲取寬度
int Width = MeasureSpec.getSize(widthMeasureSpec);
// 設(shè)置當(dāng)前控件寬高
setMeasuredDimension(parentWidth, (int) (parentWidth/RATIO));
}
}
以上做法,可以確定FrameLayout的寬高比一定是16:9, 但是如果此ViewGroup包含childView, 那么childView將不顯示, 因?yàn)椴]有主動(dòng)去measureChildren
正確的onMeasure回調(diào)應(yīng)該這樣處理
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 父控件是否是固定值或者是match_parent
int mode = MeasureSpec.getMode(widthMeasureSpec);
if (mode == MeasureSpec.EXACTLY) {
// 得到父容器的寬度
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
// 得到子控件的寬度
int childWidth = parentWidth - getPaddingLeft() - getPaddingRight();
// 計(jì)算子控件的高度
int childHeight = (int) (childWidth / RATIO + 0.5f);
// 計(jì)算父控件的高度
int parentHeight = childHeight + getPaddingBottom() + getPaddingTop();
// note 必須測(cè)量子控件,確定孩子的大小
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);
measureChildren(childWidthMeasureSpec, childHeightMeasureSpec);
// 測(cè)量
setMeasuredDimension(parentWidth, parentHeight);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}