我想有一个imageView是一个完美的广场,无论高度

我想有一个imageView是一个完美的广场,无论高度

问题描述:

我有一个imageView行布局,我用于recyclerView。该imageView高度设置为match_parent,但因为它是一个完美的正方形,所以我无法对imageView宽度进行硬编码。我想有一个imageView是一个完美的广场,无论高度

我需要的是设置imageView宽度时显示它,因为宽度设置为wrap_contentmatch_parent是完全一样的高度imageView的方式抛出的其余部分因为它是矩形的,相当大的图像,因此布局关闭。

任何帮助,将不胜感激。

你可以做这样的事情:

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比这种观点: enter image description here

+0

我没有用你竖起的FrameLayout代码,但在约束布局尖端的伎俩。我还没有很多工作,但我一定会考虑它。谢谢您的帮助! – NielJ