7
votes

I have an ImageView in my xml -

<ImageView
    android:id="@+id/image"
    android:layout_centerHorizontal="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"                     
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"/>

I am using Glide library to fetch image from an url and set that into the ImageView.

All i want is to match the width of image with parent width and then adjust the height of image without affecting the aspect ratio.

if the image dimension is very less, it should be expanded to match parent width and if image dimension are more than screen size it should be shrinked to match parent width.

ImageView img = (ImageView) findViewById("image");
Glide.with(this).load("url here").into(img);

Which scaleType should i use ?
Is it possible in XML or it needs java code ?

Thanks in advance. :)

4

4 Answers

8
votes

It is possible from the xml. I achieved it using the following code.

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

Scale XY scales the image using FILL and adjust view bounds preserves the aspect ratio. I do not think you need center horizontal property.

After this I called a photo loader library to just download the image into the image view.

2
votes

use android:scaleType:fitXY

<ImageView
android:id="@+id/image"
android:layout_centerHorizontal="true"
android:scaleType="fitXY"
android:layout_width="match_parent"
android:layout_height="wrap_content"                     
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>

and java code

Glide.with(this).load(url)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(img);
2
votes

It helps me. Just use in imageView xml

android:adjustViewBounds="true"

And add override in glide:

 GlideApp.with(context)
            .load(url)
            .override(Resources.getSystem().getDisplayMetrics().widthPixels)
            .into(imageView)
0
votes

You may use ConstraintLayout for this purpose.

You can set the view size to a ratio such as 16:9 if at least one of the view dimensions is set to "match constraints" (0dp)

As quoted from android developers. Also you can refer this medium article for reference on how to achieve this ratio thing.