我希望通过点击底部按钮来更改RecyclerView中的所有item视图
我只需更改视图类型变量并调用notifyDataSetChanged()
来通知适配器,但不更改任何内容。
private void ChangeAdapterView(){
if (viewType==0) {
StuffAdapter.ViewType=++viewType;
recyclerView.getAdapter().notifyDataSetChanged();
}
else if (viewType==1){
viewType=0;
StuffAdapter.ViewType=viewType;
recyclerView.getAdapter().notifyDataSetChanged();
}
}
注意: 我使用弹性布局,不需要改变span的大小,我只想改变视图。
public class StuffAdapter extends RecyclerView.Adapter< StuffAdapter.ViewHolder> {
private final Realm realm;
private final String base;
public static int ViewType=0;
public static void setViewType(int viewType) {
ViewType = viewType;
}
Picasso picasso;
Context context;
StoreView communicator;
SessionManager sessionManager;
List<StuffPOJO> data;
int sellerId;
public StuffAdapter(@Nullable List<StuffPOJO> data,
Picasso picasso, Context context,StoreView communicator) {
this.context=context;
this.picasso=picasso;
this.data=data;
base=context.getResources().getString(R.string.base_url);
this.communicator=communicator;
sessionManager=new SessionManager(context);
sellerId = sessionManager.getSellerId();
}
@NonNull
@Override
public StuffAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType==0)
return new StuffAdapter.ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_stuff1, parent, false));
else
return new StuffAdapter.ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_stuff2, parent, false));
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
StuffPOJO obj = getItem(position);
holder.bindView(obj);
}
@Override
public int getItemCount() {
return data.size();
}
@Nullable
public StuffPOJO getItem(int index) {
return data.get(index);
}
public void updateData(@Nullable List<StuffPOJO> list) {
Timber.w("updateData :" + list.size());
int size=this.data.size()+1;
data.addAll(list);
notifyItemRangeInserted(size,list.size());
}
public void reSetData(@Nullable List<StuffPOJO> list){
data.clear();
data.addAll(list);
notifyDataSetChanged();
}
@Override
public int getItemViewType(int position) {
return ViewType;
}
}
答案更好地使用静态变量作为引用视图类型,以避免像这样的错误链接
private void ChangeAdapterView(){
if (viewType==0) {
viewType++;
stuffAdapter.setViewType(StuffAdapter.LAYOUT_ITEM_LANDSCAPE);
stuffAdapter.notifyDataSetChanged();
}
else if (viewType==1){
viewType=0;
stuffAdapter.setViewType(StuffAdapter.LAYOUT_ITEM_PORTRAIN);
stuffAdapter.notifyDataSetChanged();
}
}