How to update RecyclerView Adapter Data?

前端 未结 13 2308
误落风尘
误落风尘 2020-11-22 03:48

Trying to figure out what is the issue with updating RecyclerView\'s Adapter.

After I get a new List of products, I tried to:

  1. Update t

13条回答
  •  一向
    一向 (楼主)
    2020-11-22 04:24

    These methods are efficient and good to start using a basic RecyclerView.

    private List items;
    
    public void setItems(List 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 newItems)
    {
        int position = items.size() + 1;
        newItems.addAll(newItems);
        notifyItemChanged(position, newItems);
    }
    
    public void addItems(List 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();
    }
    

    You can implement them inside of an Adapter Class or in your Fragment or Activity but in that case you have to instantiate the Adapter to call the notification methods. In my case I usually implement it in the Adapter.

提交回复
热议问题