Android 关于RecycleView瀑布流item换位

项目需要使用瀑布流,看了下感觉还挺容易,结果上下滑动的时候遇到item换位问题
<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/mRecyc"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    />
看了别人的解决方法,结果还是不行,最后才发现,是我把recycleview高度设成了wrap_content

附带解决方法

//声明瀑布流的布局方式: 2列,垂直方向
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
//为recyclerView设置布局管理器
mRecyc.setLayoutManager(staggeredGridLayoutManager);

staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);

在adapter内,

Map<Integer, Integer> heightArray = new HashMap<>();使用map保存已加载的view的高度
if (heightArray.get(i) == null) {
    int height = 0;  

    ConstraintLayout.LayoutParams imageParams = (ConstraintLayout.LayoutParams) secKillViewHolder.mImage_video.getLayoutParams();
    imageParams.height = height;
    secKillViewHolder.mImage_video.setLayoutParams(imageParams);
    heightArray.put(i, height);

} else {

    int height = heightArray.get(i);
    ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) secKillViewHolder.mImage_video.getLayoutParams();
    layoutParams.height = height;
    secKillViewHolder.mImage_video.setLayoutParams(layoutParams);
}

Glide.with(context).load(bean.getImg()).apply(requestOptions).into(secKillViewHolder.mImage_video);

还有一个顶部留白问题,我没有遇到,解决办法是

@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
    super.onScrollStateChanged(recyclerView, newState);
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager instanceof StaggeredGridLayoutManager) {
          //防止第一行顶部有空白区域
        ((StaggeredGridLayoutManager) layoutManager).invalidateSpanAssignments();
        }
}

上一篇:【Pyecharts|Scatter】通过dict配置完成实现单轴散点图


下一篇:RecycleView页面进行点击跳转设计