2017-08-08 5 views
-1

私はrecyclerViewのために使用する行レイアウトでimageViewを持っています。このimageViewの高さがはに設定されていますが、それは完全な正方形であるため、imageViewの幅をハードコーディングすることはできません。私はimageViewを高さにかかわらず完璧な四角形にしたい

は私に必要なのは、それがwrap_contentまたはmatch_parentに幅を設定するので、表示されたときにimageView高さimageViewと全く同じになるように設定する方法であるの残りの部分を投げますそれは長方形の、かなり大きい画像であるので、レイアウトをオフにする。

ご協力いただければ幸いです。

答えて

0

あなたはこのような何か行うことができます:あなたはまた、あなたの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では、高さを制約に合わせて設定すると、 enter image description here

+0

私は配置したFrameLayoutコードを使用しませんでしたが、制約レイアウトのヒントがトリックでした。私はまだそれをたくさん使っていますが、私は確かにそれを調べます。助けてくれてありがとう! – NielJ

関連する問題