2017-08-08 29 views
-1

我有一個imageView行佈局,我用於recyclerView。該imageView高度設置爲match_parent,但因爲它是一個完美的正方形,所以我無法對imageView寬度進行硬編碼。我想有一個imageView是一個完美的廣場,無論高度

我需要的是設置imageView寬度時顯示它,因爲寬度設置爲wrap_contentmatch_parent是完全一樣的高度imageView的方式拋出的其餘部分因爲它是矩形的,相當大的圖像,因此佈局關閉。

任何幫助,將不勝感激。

回答

0

你可以做這樣的事情:

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