ImageView use parent layout height

1.1k Views Asked by At

I'm having the same problem as this question but the answers there don't solve the problem. I've subclassed ImageView, and overriden onMeasure like so:

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
    this.setMeasuredDimension(this.getMeasuredHeight(), this.getMeasuredHeight());
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

This doesn't change anything, and if I try using the code from the answers of the linked post, the ImageView becomes invisible (0 width/height) because the heightMeasureSpec is 0, and MeasureSpec.getSize(heightMeasureSpec) is also 0.

The goal is to have the ImageView be as tall as the parent view, and have the width be the same (as the image is square).Screenshot

Edit: here is my ImageView in the layout XML:

<ImageView
    android:id="@+id/thumbnail"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_alignBottom="@+id/bottomtext"
    android:layout_alignParentLeft="true"
    android:layout_alignTop="@+id/toptext"
    android:adjustViewBounds="true"
    android:padding="4dp"
    android:scaleType="centerCrop" />
3

There are 3 best solutions below

2
On

No need to subclass the `ImageView'. Just do this

<ImageView
            android:id="@+id/slider_image"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:scaleType="fitXY" />
1
On

use following field in ImageView

android:scaleType="fitXY"
android:adjustViewBounds="true"
0
On

As described here,you can get the height of the layout at runtime. Get it and set it to imageview's width. And the image will become exact square.