android瀑布流,完美解决滑动过程中item位置错乱,下拉刷新顶部空白,加载更多顶部错乱等问题
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.moo611:StaggerdRecyclerView:latestversion'
}
<com.atech.staggedrv.StaggerdRecyclerView
android:id="@+id/str"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
//示例 example
public class FakeModel implements StaggedModel {
private int width;
private int height;
private int resourceId;
public FakeModel(int width, int height, int resourceId){
this.width = width;
this.height = height;
this.resourceId = resourceId;
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
@Override
public String getTitle() {
return null;
}
@Override
public String getThumb() {
return null;
}
@Override
public int localResorce() {
return resourceId;
}
}
class MyAdapter<T extends StaggedModel> extends StaggedAdapter<T> {
MyAdapter(Context c) {
super(c);
}
@Override
public RecyclerView.ViewHolder addViewHolder(ViewGroup viewGroup, int i) {
//绑定自定义的viewholder
View v = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_item_layout,viewGroup,false);
return new MyHolder(v);
}
@Override
public void bindView(RecyclerView.ViewHolder viewHolder, int i) {
MyHolder myHolder = (MyHolder)viewHolder;
// 在加载图片之前设定好图片的宽高,防止出现item错乱及闪烁
ViewGroup.LayoutParams layoutParams = myHolder.img.getLayoutParams();
layoutParams.height = datas.get(i).getHeight();
myHolder.img.setLayoutParams(layoutParams);
myHolder.img.setImageResource(datas.get(i).localResorce());
}
}
class MyHolder extends RecyclerView.ViewHolder{
ImageView img;
public MyHolder(@NonNull View itemView) {
super(itemView);
img = itemView.findViewById(R.id.img);
}
}
MyAdapter<FakeModel> staggedAdapter;
StaggerdRecyclerView str;
private List<FakeModel> datas = new ArrayList<>();
...
str = findViewById(R.id.str);
staggedAdapter = new MyAdapter<>(this);
str.link(staggedAdapter,2);
str.addCallbackListener(new LoadMoreAndRefresh() {
@Override
public void onLoadMore() {
staggedAdapter.loadMore(datas); //加载更多
}
@Override
public void onRefresh() {
staggedAdapter.refresh(datas); //下拉刷新
}
});
refresh();
...
str.addAnimation(R.anim.right_to_left);
str.addDecoration(new GridItemDecoration(this,10));
str.enableRefresh(false);
str.enableLoadMore(false);
在Recyclerview滑动过程中,由于缓存复用机制,会对Item进行重绘, 如果不确定imageview的宽高,就会造成位置错乱和闪烁。
使用 notifyDataSetChanged()方法做刷新时,会触发StaggeredGridLayoutManager 的onItemsChanged 方法,导致item的spanIndex重现进行计算,item所在列的位置出现了变化,导致了顶部空白。而用notifyItemRangeInserted,notifyItemRangeChanged做局部刷新时则不会引起变化。