使用 StaggeredGridLayoutManager 时阻止项目四处移动

Stop items from moving around when using StaggeredGridLayoutManager

我在 android 中将 recyclerview 与 staggredGridLayoutManager 一起使用。问题是,有时当滚动项目四处移动以适应屏幕时。通常这没什么好担心的,但在我的情况下,它把一切都搞砸了! 那么有没有办法阻止这种行为呢?不仅仅是动画。整个项目重新排列的东西。 谢谢

如果您使用的是 Picasso,那么首先创建一个自定义 ImageView

public class DynamicHeightImageView extends ImageView  {

private double mHeightRatio;

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

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

//Here we will set the aspect ratio
public void setHeightRatio(double ratio) {
    if (ratio != mHeightRatio) {
        mHeightRatio = ratio;
        requestLayout();
    }
}

public double getHeightRatio() {
    return mHeightRatio;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (mHeightRatio > 0.0) {
        // set the image views size
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = (int) (width * mHeightRatio);
        setMeasuredDimension(width, height);
    } else {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}


}

然后在你的 onBindViewHolder

Picasso.with(context).load(modal.image.mediumUrl).into(holder.profileImage, new Callback() {
            @Override
            public void onSuccess() {
                holder.profileImage.setHeightRatio(holder.profileImage.getHeight()/holder.profileImage.getWidth());
            }

            @Override
            public void onError() {

            }
        });

使用 Randy 的回答中建议的 ImageView,您可以对 Glide 执行相同的操作:

  Glide.with(context)
            .load(imageURL)
            .asBitmap()
            .dontAnimate()
            .fitCenter()
            .diskCacheStrategy(DiskCacheStrategy.RESULT)
            .into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {

                    if (bitmap != null)
                    {
                        holder.image.setHeightRatio(bitmap.getHeight()/bitmap.getWidth());
                        holder.image.setImageBitmap(bitmap);
                    }
                }
            });

经过大量搜索后,我意识到没有可行的解决方案! StaggeredGridLayoutManager 将重新排列其项目,导致项目四处移动。除非我们写一个完全定制的 LayoutManager 版本不是很容易,我怀疑是否有办法处理这个问题。

要禁用重新排列,只需调用 recyclerView.itemAnimator = null

此外,如果您使用 ImageViews,请确保将 adjustViewBounds 设置为 true