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?
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!
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);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With