最近项目中使用的多种样式的布局是通过RecyclerView.addHeadView()来实现的,一个RecyclerView中嵌套了多个RecyclerView,导致代码很冗余很丑陋,而且性能也不好,就考虑重构,在这先写个demo https://github.com/553474628/RecyclerViewTest
效果图如下:
核心就是在Adapter里用不同的type去处理数据,然后在Activity中当数据改变时去调用adapter.notifyDataSetChanged(),用数据去渲染UI
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
switch (viewType) {
case VIEW_TYPE_1:
return new ViewHolderType1(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_1, parent, false));
case VIEW_TYPE_2:
return new ViewHolderType2(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_2, parent, false));
case VIEW_TYPE_3:
return new ViewHolderType3(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_3, parent, false));
case VIEW_TYPE_4:
return new ViewHolderType4(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_4, parent, false));
default:
Log.d("error", "ViewHolder is null");
return null;
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case VIEW_TYPE_1:
((ViewHolderType1) holder).bindViewHolder(mData.get(position));
break;
case VIEW_TYPE_2:
((ViewHolderType2) holder).bindViewHolder(mData.get(position));
break;
case VIEW_TYPE_3:
((ViewHolderType3) holder).bindViewHolder(mData.get(position));
break;
case VIEW_TYPE_4:
((ViewHolderType4) holder).bindViewHolder(mData.get(position), mListener);
break;
default:
break;
}
}
小tips:
如果要隐藏RecyclerView中的item,只设置View.GONE是无效的,会导致该区域还在只不过显示为空白(已采坑),然后百度看了大佬们的解决办法是说要设置Layout的宽高