Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView with StaggeredGridLayoutManager with images loading from Glide

I am having a problem showing RecyclerView with StaggeredGridLayoutManager whose item contain an imageview and the image is loaded in imageview using glide. The problem i am facing is that after images getting loaded they are not staggered and are of equal sizes as well there is a big gap between two columns. How to vary the height of images with no gaps in columns?

like image 251
Passiondroid Avatar asked Mar 22 '16 08:03

Passiondroid


3 Answers

I was having the same issue. What worked for me was to set android:adjustViewBounds="true" for my ImageView. I'm not even setting scaleType.

Here's the full content of my layout file, item.xml.

<?xml version="1.0" encoding="utf-8"?>
<ImageView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gif_image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorFiller"
    android:adjustViewBounds="true"/>

Hope this helps!

like image 174
Don Shrout Avatar answered Nov 15 '22 14:11

Don Shrout


Add android:adjustViewBounds="true" to the ImageView in the item layout and use CenterCrop and FitCenter in Glide like this:

Glide.with(vh.view.getContext())
        .load(item.getUrl())
        .centerCrop()
        .fitCenter()
        .thumbnail(0.3f)
        .placeholder(R.drawable.img_placeholder)
        .into(vh.image);
like image 44
Alektas Avatar answered Nov 15 '22 14:11

Alektas


Finally i am able to find out the soultion. I had to create the custom imageview to vary its aspect ratio in Staggered Recycler View.

public class DynamicHeightNetworkImageView extends ImageView {
private float mAspectRatio = 1.5f;

public DynamicHeightNetworkImageView(Context context) {
    super(context);
}

public DynamicHeightNetworkImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public DynamicHeightNetworkImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public void setAspectRatio(float aspectRatio) {
    mAspectRatio = aspectRatio;
    requestLayout();
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int measuredWidth = getMeasuredWidth();
    setMeasuredDimension(measuredWidth, (int) (measuredWidth / mAspectRatio));
}
}

Then in onBindViewHolder of the adapter i set the aspect ratio of the image by -

Picasso.with(this).load(THUMB_URL).into(holder.thumbnailView);
holder.thumbnailView.setAspectRatio(ASPECT_RATIO));
like image 22
Passiondroid Avatar answered Nov 15 '22 13:11

Passiondroid