你可以做這樣的事情:
public class FixedAspectRatioFrameLayout extends FrameLayout {
private float ratio;
public FixedAspectRatioFrameLayout(@NonNull Context context) {
super(context);
}
public FixedAspectRatioFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attributeSet) {
fillFromAttrs(context, attributeSet);
}
private void fillFromAttrs(Context context, AttributeSet attributeSet) {
TypedArray array = context.obtainStyledAttributes(attributeSet, R.styleable.FixedAspectRatioFrameLayout);
ratio = array.getFloat(R.styleable.FixedAspectRatioFrameLayout_ratio, 0);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int originalWidth = MeasureSpec.getSize(widthMeasureSpec);
int originalHeight = MeasureSpec.getSize(heightMeasureSpec);
int finalWidth = originalWidth;
int finalHeight = originalHeight;
if (ratio != 0) {
if (originalHeight == 0) {
finalHeight = (int) (originalWidth/ratio);
} else if (originalWidth == 0) {
finalWidth = (int) (originalHeight * ratio);
}
}
super.onMeasure(
MeasureSpec.makeMeasureSpec(finalWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(finalHeight, MeasureSpec.EXACTLY)
);
}
}
您還需要在您的RES /價值/ attrs.xml指定屬性 「比」:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="FixedAspectRatioFrameLayout">
<attr name="ratio" format="float"/>
</declare-styleable>
</resources>
所以現在你可以指定,例如,根據需要設置此FrameLayout的高度,將寬度設置爲0dp並將比率設置爲1,然後將ImageView放入此FrameLayout中。另外,在ConstraintLayout中,如果將高度設置爲與約束匹配,則可以pecify比這種觀點:
我沒有用你豎起的FrameLayout代碼,但在約束佈局尖端的伎倆。我還沒有很多工作,但我一定會考慮它。謝謝您的幫助! – NielJ