如何更新回收视图适配器数据?
RecyclerView
ArrayList
recyclerView
adapter.notifyDataSetChanged()
recyclerView.setAdapter(new RecyclerViewAdapter(newArrayList))
Adapter
public void updateData(ArrayList<ViewModel> viewModels) { items.clear(); items.addAll(viewModels); notifyDataSetChanged();}
public void removeItem(int position) { items.remove(position); notifyItemRemoved(position);}
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements View.OnClickListener { private ArrayList<ViewModel> items; private OnItemClickListener onItemClickListener; public RecyclerViewAdapter(ArrayList<ViewModel> items) { this.items = items; } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler, parent, false); v.setOnClickListener(this); return new ViewHolder(v); } public void updateData(ArrayList<ViewModel> viewModels) { items.clear(); items.addAll(viewModels); notifyDataSetChanged(); } public void addItem(int position, ViewModel viewModel) { items.add(position, viewModel); notifyItemInserted(position); } public void removeItem(int position) { items.remove(position); notifyItemRemoved(position); }
因此,如何实际更新适配器数据以显示新接收的项?
翻翻过去那场雪
ABOUTYOU
相关分类