Okn
Okn

Reputation: 698

Android - StaggeredGrid wrong items disposition

I have a problem with my Recycler view and StaggeredGrid which cut the width by 2. I load images into items with Picasso and when I load image first time, they are disposed strangely in the recycler view. After reloading, everything seems good.

I think problem come from image loading : the StaggeredGrid doesn't know the image height the first time, but know after reloading because of cache.

How can i solve this problem ?

enter image description here

Upvotes: 4

Views: 2188

Answers (3)

YLS
YLS

Reputation: 1565

This happens because the holder dose not recognize the width and height of the Image view when you scroll up and down. It clears the upper view when you scroll down and vice versa.

Use like this :

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {

MyViewHolder vh = (MyViewHolder) viewHolder;
ImageModel item = imageModels.get(position);
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams)vh.imageView.getLayoutParams();
float ratio = item.getHeight() / item.getWidth();
rlp.height = (int) (rlp.width * ratio);
vh.imageView.setLayoutParams(rlp);
vh.positionTextView.setText("pos: " + position);
vh.imageView.setRatio(item.getRatio());
Picasso.with(mContext).load(item.getUrl()).placeholder(PlaceHolderDrawableHelper.getBackgroundDrawable(position)).into(vh.imageView);
}

For clear see this link: Picasso/Glide-RecyclerView-StaggeredGridLayoutManager

Upvotes: 0

Okn
Okn

Reputation: 698

Solved by changing gap strategy to :

StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
    manager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
    recyclerView.setLayoutManager(manager);

Change the position of items automatically

Upvotes: 0

ian.shaun.thomas
ian.shaun.thomas

Reputation: 3488

I think you have answered your own question. You need to load the images/determine their dimensions before adding the data to the recycler.

Upvotes: 1

Related Questions