btalb
btalb

Reputation: 7037

Android ImageView - Fill width and Resize to Maintain Aspect Ratio

I have a row View that I am using in a ListView.

This RowView consists of an ImageView on the left and a TextView on the right in a horizontal LinearLayout where the image is given 40% of the space and the text the remaining 60%.

I want the layout to handle the resizing of the image in the ImageView in the following manner:

  1. Stretch the image horizontally so that it fills up given 40% of the LinearLayout
  2. Resize the ImageView vertically to maintain the original aspect ratio

This is my approach to the layouts:

protected class RowView extends LinearLayout {
public ImageView iv = null;
public TextView tv = null;

private LinearLayout.LayoutParams ivlp = null;
private LinearLayout.LayoutParams tvlp = null;

public RowView(Context ct) {
    super(ct);

    setOrientation(LinearLayout.HORIZONTAL);

    // Create the views
    iv = new ImageView(ct);
    ivlp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.4f);
    iv.setLayoutParams(ivlp);
    iv.setAdjustViewBounds(true);
    iv.setScaleType(ScaleType.FIT_XY);

    tv = new TextView(ct);
    tvlp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 0.4f);
    tv.setLayoutParams(tvlp);
    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);

    // Add the views
    addView(iv);
    addView(tv);
}

}

The result I am getting is something like this:

enter image description here

From what I understand:

What am I doing wrong? It seems wrong that something this simple could be so difficult?

Or do I actually have to go to the effort of extending an ImageView and Overriding onMeasure to force the resizing and aspect ratio?

Or is there a clever trick with Matrix to get the job done?

Upvotes: 4

Views: 7816

Answers (2)

erkinyldz
erkinyldz

Reputation: 688

I believe this is what you are looking for:

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/myImage"
    android:scaleType="fitCenter"
    android:adjustViewBounds="true" />

Upvotes: 4

Jason Robinson
Jason Robinson

Reputation: 31283

Remove the scale type completely. Also, I think you might have misunderstood what setAdjustViewBounds does. If an image is scaled, the bitmap in the ImageView is scaled, but not the ImageView. Setting setAdjustViewBounds to true will assure that the ImageView's bounds will always match the drawn bitmap's bounds.

Upvotes: 0

Related Questions