我現在用下面的代碼解決了這個。值得一提的是,我最重要的課程是自定義ViewGroup
自定義子項,全部使用繼承的onMeasure
。孩子們在建造時被創造和補充,當然我認爲這是必要的。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
float width = MeasureSpec.getSize(widthMeasureSpec);
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
float height = MeasureSpec.getSize(heightMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
float nominalHeight = getResources().getInteger(R.integer.nominalheight);
float nominalWidth = getResources().getInteger(R.integer.nominalwidth);
float aspectRatio = nominalWidth/nominalHeight;
if(widthMode == MeasureSpec.UNSPECIFIED) { //conform width to height
width = height * aspectRatio;
}
else if (heightMode == MeasureSpec.UNSPECIFIED) { //conform height to width
height = width/aspectRatio;
}
else if(width/height > aspectRatio //too wide
&& (widthMode == MeasureSpec.AT_MOST)
) {
width -= (width - height * aspectRatio);
}
else if(width/height < aspectRatio //too tall
&& (heightMode == MeasureSpec.AT_MOST)
) {
height -= (height - width/aspectRatio);
}
int newWidthMeasure = MeasureSpec.makeMeasureSpec((int)width, MeasureSpec.AT_MOST);
int newHeightMeasure = MeasureSpec.makeMeasureSpec((int)height, MeasureSpec.AT_MOST);
measureChildren(newWidthMeasure, newHeightMeasure);
setMeasuredDimension((int)width, (int)height);
}
我用資源中名義矩形來定義縱橫比,但顯然還有很多其他方法可以做到這一點。
感謝Josephus Villarey誰指我在onMeasure(...)
首先。
謝謝,這真的很有用:) –
我已經把我的實現作爲答案,但提示是讓我在那裏的步驟 - 再次感謝! –