我试图弄清楚更新RecyclerView的适配器有什么问题。

在我得到一个新的产品清单后,我试着:

Update the ArrayList from the fragment where recyclerView is created, set new data to adapter, and then call adapter.notifyDataSetChanged(); it did not work. Create a new adapter, as others did, and it worked for them, but there wasn't any change for me: recyclerView.setAdapter(new RecyclerViewAdapter(newArrayList)) Create a method in Adapter which updates the data as follows: public void updateData(ArrayList<ViewModel> viewModels) { items.clear(); items.addAll(viewModels); notifyDataSetChanged(); } Then I call this method whenever I want to update the data list; it did not work. To check if I can modify the recyclerView in any way, and I tried to remove at least an item: 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);
    }


    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        ViewModel item = items.get(position);
        holder.title.setText(item.getTitle());
        Picasso.with(holder.image.getContext()).load(item.getImage()).into(holder.image);
        holder.price.setText(item.getPrice());
        holder.credit.setText(item.getCredit());
        holder.description.setText(item.getDescription());

        holder.itemView.setTag(item);
    }


    @Override
    public int getItemCount() {
        return items.size();
    }


    @Override
    public void onClick(final View v) {
        // Give some time to the ripple to finish the effect
        if (onItemClickListener != null) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    onItemClickListener.onItemClick(v, (ViewModel) v.getTag());
                }
            }, 0);
        }
    }

    protected static class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView image;
        public TextView price, credit, title, description;

        public ViewHolder(View itemView) {
            super(itemView);
            image = (ImageView) itemView.findViewById(R.id.image);
            price = (TextView) itemView.findViewById(R.id.price);
            credit = (TextView) itemView.findViewById(R.id.credit);
            title = (TextView) itemView.findViewById(R.id.title);
            description = (TextView) itemView.findViewById(R.id.description);
        }
    }

    public interface OnItemClickListener {

        void onItemClick(View view, ViewModel viewModel);

    }
}

我启动RecyclerView,如下所示:

recyclerView = (RecyclerView) view.findViewById(R.id.recycler);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 5));
adapter = new RecyclerViewAdapter(items);
adapter.setOnItemClickListener(this);
recyclerView.setAdapter(adapter);

那么,如何实际更新适配器数据以显示新接收到的项呢?


问题是gridView的布局是这样的:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:tag="catalog_fragment"
    android:layout_height="match_parent">

    <FrameLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="false"/>

        <ImageButton
            android:id="@+id/fab"
            android:layout_gravity="top|end"
            style="@style/FabStyle"/>

    </FrameLayout>
</LinearLayout>

然后我只是删除线性布局,并使FrameLayout作为父布局。


当前回答

这个很好试试。

  ArrayList.remove(position);
  notifyItemRemoved(position);
  notifyDataSetChanged();

其他回答

另一种选择是使用diffutil。它将把原始列表与新列表进行比较,如果有更改,则使用新列表作为更新。

基本上,我们可以使用DiffUtil来比较旧数据和新数据,并让它代表你调用notifyItemRangeRemoved, notifyItemRangeChanged和notifyItemRangeInserted。

一个使用diffUtil代替notifyDataSetChanged的快速示例:

DiffResult diffResult = DiffUtil
                .calculateDiff(new MyDiffUtilCB(getItems(), items));

//any clear up on memory here and then
diffResult.dispatchUpdatesTo(this);

//and then, if necessary
items.clear()
items.addAll(newItems)

我做calculateDiff工作的主线程,如果它是一个大列表使用AsyncListDiffer

我用不同的方法解决了同样的问题。 我没有数据。我正在等待它从后台线程,所以开始与一个空列表。

mAdapter = new ModelAdapter(getContext(), new ArrayList<Model>());
// Then when I get data

mAdapter.update(response.getModelList());
// And update it in my adapter

public void update(ArrayList<Model> modelList){
    adapterModelList.clear();
    for (Product model: modelList) {
        adapterModelList.add(model);
    }
   mAdapter.notifyDataSetChanged();
}

就是这样。

如果上面的评论对你不起作用,这可能意味着问题出在其他地方。

我发现解决方案的一个地方是我将列表设置到适配器的方式。在我的活动中,列表是一个实例变量,当任何数据发生变化时,我直接改变它。由于它是一个参考变量,所以发生了一些奇怪的事情。

因此,我将引用变量更改为本地变量,并使用另一个变量更新数据,然后传递给前面回答中提到的addAll()函数。

这些方法非常有效,可以很好地开始使用一个基本的RecyclerView。

private List<YourItem> items;

public void setItems(List<YourItem> newItems)
{
    clearItems();
    addItems(newItems);
}

public void addItem(YourItem item, int position)
{
    if (position > items.size()) return;

    items.add(item);
    notifyItemInserted(position);
}

public void addMoreItems(List<YourItem> newItems)
{
    int position = items.size() + 1;
    newItems.addAll(newItems);
    notifyItemChanged(position, newItems);
}

public void addItems(List<YourItem> newItems)
{
    items.addAll(newItems);
    notifyDataSetChanged();
}

public void clearItems()
{
    items.clear();
    notifyDataSetChanged();
}

public void addLoader()
{
    items.add(null);
    notifyItemInserted(items.size() - 1);
}

public void removeLoader()
{
    items.remove(items.size() - 1);
    notifyItemRemoved(items.size());
}

public void removeItem(int position)
{
    if (position >= items.size()) return;

    items.remove(position);
    notifyItemRemoved(position);
}

public void swapItems(int positionA, int positionB)
{
    if (positionA > items.size()) return;
    if (positionB > items.size()) return;

    YourItem firstItem = items.get(positionA);

    videoList.set(positionA, items.get(positionB));
    videoList.set(positionB, firstItem);

    notifyDataSetChanged();
}

你可以在一个适配器类或你的片段或活动中实现它们,但在这种情况下,你必须实例化适配器来调用通知方法。在我的情况下,我通常在适配器中实现它。

我建议你探索一下DiffUtil。它还提高了RecyclerView在处理列表更新时的性能。

在适配器中定义一个变量: differList = AsyncListDiffer(this, this.callback); differList.submitList(列表)

在这里,列表可以是您最初的原始列表,也可以只是一个空列表,前提是您稍后将更新它。

实现回调函数: 私有val回调:DiffUtil。ItemCallback<Item> = object: DiffUtil.ItemCallback<Item>() { override fun areitemssame (oldItem: Item, newItem: Item) = oldItem。id == newItem.id override fun arecontentssame (oldItem: Item, newItem: Item) = oldItem == newItem } 同样,在同一个适配器中,您将有一些公共函数来设置列表。 setData(list: list <Item>) { differList.submitList(列表) //是的,就是这样! }

现在,在你对你的列表做了任何改变之后(插入/更新/删除),只需从你的片段/活动中调用这个setData(列表)。 mAdapter.setData(列表)

容易,对吧?