How to update RecyclerView Adapter Data?

前端 未结 13 2315
误落风尘
误落风尘 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:36

    I strongly recommend you to use [DiffUtil.ItemCallback][1] to handle the change in RecyclerView.Adapter

    
     fun setData(data: List) {
            val calculateDiff = DiffUtil.calculateDiff(DiffUtilCallback(items, data))
            items.clear()
            items += data
            calculateDiff.dispatchUpdatesTo(this)
        }
    

    under the hood it handles most of the things with AdapterListUpdateCallback:

    /**
     * ListUpdateCallback that dispatches update events to the given adapter.
     *
     * @see DiffUtil.DiffResult#dispatchUpdatesTo(RecyclerView.Adapter)
     */
    public final class AdapterListUpdateCallback implements ListUpdateCallback {
        @NonNull
        private final RecyclerView.Adapter mAdapter;
    
        /**
         * Creates an AdapterListUpdateCallback that will dispatch update events to the given adapter.
         *
         * @param adapter The Adapter to send updates to.
         */
        public AdapterListUpdateCallback(@NonNull RecyclerView.Adapter adapter) {
            mAdapter = adapter;
        }
    
        /** {@inheritDoc} */
        @Override
        public void onInserted(int position, int count) {
            mAdapter.notifyItemRangeInserted(position, count);
        }
    
        /** {@inheritDoc} */
        @Override
        public void onRemoved(int position, int count) {
            mAdapter.notifyItemRangeRemoved(position, count);
        }
    
        /** {@inheritDoc} */
        @Override
        public void onMoved(int fromPosition, int toPosition) {
            mAdapter.notifyItemMoved(fromPosition, toPosition);
        }
    
        /** {@inheritDoc} */
        @Override
        public void onChanged(int position, int count, Object payload) {
            mAdapter.notifyItemRangeChanged(position, count, payload);
        }
    }
    
    

提交回复
热议问题