あなたはこのような何か行うことができます:あなたはまた、あなたのres /値/ attrs.xmlに属性 "比" を指定する必要が
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)
);
}
}
:
<?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では、高さを制約に合わせて設定すると、
私は配置したFrameLayoutコードを使用しませんでしたが、制約レイアウトのヒントがトリックでした。私はまだそれをたくさん使っていますが、私は確かにそれを調べます。助けてくれてありがとう! – NielJ