androidx.recyclerview.widget.DiffUtil Java Examples

The following examples show how to use androidx.recyclerview.widget.DiffUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ColumnSortHandler.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void swapItems(List<ISortableModel> oldRowHeader,
                       List<ISortableModel> newRowHeader,
                       List<List<ISortableModel>> newColumnItems,
                       SortState sortState
) {

    // Set new items without calling notifyCellDataSetChanged method of CellRecyclerViewAdapter
    mRowHeaderRecyclerViewAdapter.setItems(newRowHeader, !mEnableAnimation);
    mCellRecyclerViewAdapter.setItems(newColumnItems, !mEnableAnimation);

    if(mEnableAnimation) {
        // Find the differences between old cell items and new items.
        final RowHeaderSortCallback diffCallback = new RowHeaderSortCallback(oldRowHeader, newRowHeader);
        final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);

        diffResult.dispatchUpdatesTo(mRowHeaderRecyclerViewAdapter);
        diffResult.dispatchUpdatesTo(mCellRecyclerViewAdapter);
    }

    for (ColumnSortStateChangedListener listener : columnSortStateChangedListeners) {
        listener.onRowHeaderSortStatusChanged(sortState);
    }
}
 
Example #2
Source File: SlimAdapter.java    From SlimAdapter with MIT License 6 votes vote down vote up
public SlimAdapter updateData(List<?> data) {
    if (moreLoader != null) {
        moreLoader.reset();
    }
    if (diffCallback == null || getItemCount() == 0 || data == null || data.size() == 0) {
        this.data = data;
        if (Looper.myLooper() == Looper.getMainLooper()) {
            notifyDataSetChanged();
        } else {
            uiHandler.removeMessages(WHAT_NOTIFY_DATA_SET_CHANGED);
            uiHandler.sendEmptyMessage(WHAT_NOTIFY_DATA_SET_CHANGED);
        }
    } else {
        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new SlimDiffUtil(this.data, data, diffCallback));
        this.data = data;
        if (Looper.myLooper() == Looper.getMainLooper()) {
            diffResult.dispatchUpdatesTo(this);
        } else {
            uiHandler.removeMessages(WHAT_NOTIFY_DATA_SET_CHANGED);
            uiHandler.sendEmptyMessage(WHAT_NOTIFY_DATA_SET_CHANGED);
        }
    }
    return this;
}
 
Example #3
Source File: ColumnSortHandler.java    From TableView with MIT License 6 votes vote down vote up
public void swapItems(@NonNull List<List<ISortableModel>> newItems, int column) {

        List<List<ISortableModel>> oldItems = mCellRecyclerViewAdapter.getItems();

        // Set new items without calling notifyCellDataSetChanged method of CellRecyclerViewAdapter
        mCellRecyclerViewAdapter.setItems(newItems, !mEnableAnimation);

        if (mEnableAnimation) {
            // Find the differences between old cell items and new items.
            final ColumnSortCallback diffCallback = new ColumnSortCallback(oldItems, newItems, column);
            final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);

            diffResult.dispatchUpdatesTo(mCellRecyclerViewAdapter);
            diffResult.dispatchUpdatesTo(mRowHeaderRecyclerViewAdapter);
        }

    }
 
Example #4
Source File: ItemProvider.java    From AdapterDelegates with Apache License 2.0 6 votes vote down vote up
public Pair<List<Item>, DiffUtil.DiffResult> modify() {
    List<Item> newlist = copyCurrent();

    Item c1 = newlist.get(0).copy();
    c1.color = color();
    newlist.set(0, c1);

    Item c2 = newlist.get(5).copy();
    c2.text = c2.text + " - Updated";
    newlist.set(5, c2);

    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new ItemDiff(currentList, newlist));

    currentList = newlist;
    return Pair.create(newlist, diffResult);
}
 
Example #5
Source File: DiffList.java    From power-adapters with Apache License 2.0 6 votes vote down vote up
@NonNull
Completable overwriteUsingDiffUtil(@NonNull final List<? extends T> newContents,
                                     @NonNull final EqualityFunction<? super T> identityEqualityFunction,
                                     @NonNull final EqualityFunction<? super T> contentEqualityFunction) {
    return copyContents().switchMap(new Function<List<? extends T>, Observable<?>>() {
        @Override
        public Observable<Object> apply(List<? extends T> existingContentsCopy) throws Exception {
            return calculateDiff(existingContentsCopy, newContents, identityEqualityFunction, contentEqualityFunction)
                    .switchMap(new Function<DiffUtil.DiffResult, Observable<Object>>() {
                        @Override
                        public Observable<Object> apply(DiffUtil.DiffResult diffResult) throws Exception {
                            return applyNewContentsAndDispatchDiffNotifications(newContents, diffResult).toObservable();
                        }
                    });
        }
    }).ignoreElements();
}
 
Example #6
Source File: ItemProvider.java    From AdapterDelegates with Apache License 2.0 6 votes vote down vote up
/**
 * @return null if removement cant be executed because min list size is required
 */
@Nullable
public Pair<List<Item>, DiffUtil.DiffResult> remove() {
    if (currentList.size() <= 6) {
        return null;
    }
    List<Item> newlist = copyCurrent();

    newlist.remove(1);
    newlist.remove(3);

    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new ItemDiff(currentList, newlist));

    currentList = newlist;
    return Pair.create(newlist, diffResult);
}
 
Example #7
Source File: ManageArticleTagsActivity.java    From android-app with GNU General Public License v3.0 6 votes vote down vote up
private void updateCurrentTagList(List<Tag> newList) {
    if (currentTags.isEmpty() && newList.isEmpty()) return;

    sortTagListByLabel(newList);

    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(
            new TagListFragment.TagListDiffCallback(currentTags, newList));

    currentTags.clear();
    currentTags.addAll(newList);

    diffResult.dispatchUpdatesTo(currentTagsAdapter);

    if (currentTagsNone != null) {
        currentTagsNone.setVisibility(currentTags.isEmpty() ? View.VISIBLE : View.GONE);
    }
    if (currentTagsView != null) {
        currentTagsView.setVisibility(currentTags.isEmpty() ? View.GONE : View.VISIBLE);
    }

    updateSuggestedTagList();
}
 
Example #8
Source File: OrgUnitSelectorAdapter.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void addOrgUnits(int location, List<TreeNode> nodes) {
    List<TreeNode> nodesCopy = new ArrayList<>(treeNodes);
    nodesCopy.get(location).setOpen(!nodesCopy.get(location).isOpen());
    notifyItemChanged(location);
    if (!nodesCopy.get(location).isOpen()) {
        TreeNode parent = nodesCopy.get(location);
        List<TreeNode> deleteList = new ArrayList<>();
        boolean sameLevel = true;
        for (int i = location + 1; i < nodesCopy.size(); i++) {
            if (sameLevel)
                if (nodesCopy.get(i).getLevel() > parent.getLevel()) {
                    deleteList.add(nodesCopy.get(i));
                } else {
                    sameLevel = false;
                }
        }
        nodesCopy.removeAll(deleteList);
    } else {
        nodesCopy.addAll(location + 1, nodes);
    }

    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new TreeNodeCallback(treeNodes, nodesCopy));
    diffResult.dispatchUpdatesTo(this);
    treeNodes.clear();
    treeNodes.addAll(nodesCopy);
}
 
Example #9
Source File: ColumnSortHandler.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void swapItems(List<List<ISortableModel>> newItems, int column) {

        List<List<ISortableModel>> oldItems = (List<List<ISortableModel>>)
                mCellRecyclerViewAdapter.getItems();

        // Set new items without calling notifyCellDataSetChanged method of CellRecyclerViewAdapter
        mCellRecyclerViewAdapter.setItems(newItems, !mEnableAnimation);

        if(mEnableAnimation) {
            // Find the differences between old cell items and new items.
            final ColumnSortCallback diffCallback = new ColumnSortCallback(oldItems, newItems, column);
            final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);

            diffResult.dispatchUpdatesTo(mCellRecyclerViewAdapter);
            diffResult.dispatchUpdatesTo(mRowHeaderRecyclerViewAdapter);
        }

    }
 
Example #10
Source File: ColumnSortHandler.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void swapItems(List<List<ISortableModel>> oldItems, List<List<ISortableModel>>
        newItems, int column, List<ISortableModel> newRowHeader, SortState sortState) {

    // Set new items without calling notifyCellDataSetChanged method of CellRecyclerViewAdapter
    mCellRecyclerViewAdapter.setItems(newItems, !mEnableAnimation);
    mRowHeaderRecyclerViewAdapter.setItems(newRowHeader, !mEnableAnimation);

    if(mEnableAnimation) {
        // Find the differences between old cell items and new items.
        final ColumnSortCallback diffCallback = new ColumnSortCallback(oldItems, newItems, column);
        final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);

        diffResult.dispatchUpdatesTo(mCellRecyclerViewAdapter);
        diffResult.dispatchUpdatesTo(mRowHeaderRecyclerViewAdapter);
    }

    for (ColumnSortStateChangedListener listener : columnSortStateChangedListeners) {
        listener.onColumnSortStatusChanged(column, sortState);
    }
}
 
Example #11
Source File: BankTransferActivity.java    From shinny-futures-android with GNU General Public License v3.0 6 votes vote down vote up
private void refreshTransfer() {
    try {
        UserEntity userEntity = sDataManager.getTradeBean().getUsers().get(sDataManager.USER_ID);
        if (userEntity == null) return;
        mNewData.clear();
        for (TransferEntity transferEntity :
                userEntity.getTransfers().values()) {
            TransferEntity t = CloneUtils.clone(transferEntity);
            mNewData.add(t);
        }
        Collections.sort(mNewData);
        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new TransferDiffCallback(mOldData, mNewData), false);
        mAdapter.setData(mNewData);
        diffResult.dispatchUpdatesTo(mAdapter);
        mOldData.clear();
        mOldData.addAll(mNewData);
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example #12
Source File: ManagerConditionOrderActivity.java    From shinny-futures-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * date: 2019/8/10
 * author: chenli
 * description:
 */
public void refreshCO() {
    try {
        ConditionUserEntity userEntity = sDataManager.getConditionOrderBean().getUsers().get(sDataManager.USER_ID);
        if (userEntity == null)return;
        Map<String, ConditionOrderEntity> condition_orders = userEntity.getCondition_orders();
        mNewData.clear();
        for (ConditionOrderEntity conditionOrderEntity :
                condition_orders.values()) {
            ConditionOrderEntity t = CloneUtils.clone(conditionOrderEntity);
            mNewData.add(t);
        }
        Collections.sort(mNewData);
        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new ConditionOrderDiffCallback(mOldData, mNewData), false);
        mAdapter.setData(mNewData);
        diffResult.dispatchUpdatesTo(mAdapter);
        mOldData.clear();
        mOldData.addAll(mNewData);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #13
Source File: ColumnSortHandler.java    From TableView with MIT License 6 votes vote down vote up
private void swapItems(@NonNull List<List<ISortableModel>> oldItems, @NonNull List<List<ISortableModel>>
        newItems, int column, @NonNull List<ISortableModel> newRowHeader, @NonNull SortState sortState) {

    // Set new items without calling notifyCellDataSetChanged method of CellRecyclerViewAdapter
    mCellRecyclerViewAdapter.setItems(newItems, !mEnableAnimation);
    mRowHeaderRecyclerViewAdapter.setItems(newRowHeader, !mEnableAnimation);

    if (mEnableAnimation) {
        // Find the differences between old cell items and new items.
        final ColumnSortCallback diffCallback = new ColumnSortCallback(oldItems, newItems, column);
        final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);

        diffResult.dispatchUpdatesTo(mCellRecyclerViewAdapter);
        diffResult.dispatchUpdatesTo(mRowHeaderRecyclerViewAdapter);
    }

    for (ColumnSortStateChangedListener listener : columnSortStateChangedListeners) {
        listener.onColumnSortStatusChanged(column, sortState);
    }
}
 
Example #14
Source File: RecyclerViewAdapterHelper.java    From MultiTypeRecyclerViewAdapter with Apache License 2.0 6 votes vote down vote up
/**
 * 处理数据,通知RV刷新
 *
 * @param diffResult 返回的diffResult
 */
protected final void handleResult(DiffUtil.DiffResult diffResult) {
    checkAdapterBind();

    diffResult.dispatchUpdatesTo(getListUpdateCallback(mAdapter));

    mData.clear();
    mData.addAll(mNewData);

    HandleBase<T> pollData = mRefreshQueue.poll();
    if (pollData != null) {
        startRefresh(pollData);
    } else {
        onEnd();
    }
}
 
Example #15
Source File: TradeFragment.java    From shinny-futures-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void refreshTD() {
    if (mView == null)return;
    if (!mIsUpdate) return;
    try {
        UserEntity userEntity = sDataManager.getTradeBean().getUsers().get(sDataManager.USER_ID);
        if (userEntity == null) return;
        mNewData.clear();
        for (TradeEntity tradeEntity :
                userEntity.getTrades().values()) {
            TradeEntity t = CloneUtils.clone(tradeEntity);
            mNewData.add(t);
        }
        Collections.sort(mNewData);
        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new TradeDiffCallback(mOldData, mNewData), false);
        mAdapter.setData(mNewData);
        diffResult.dispatchUpdatesTo(mAdapter);
        mOldData.clear();
        mOldData.addAll(mNewData);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #16
Source File: GamesAdapter.java    From UpdogFarmer with GNU General Public License v3.0 6 votes vote down vote up
private void updateDataInternal(final List<Game> newGames) {
    final List<Game> oldGames = new ArrayList<>(dataSet);
    final Handler handler = new Handler(Looper.getMainLooper());
    new Thread(new Runnable() {
        @Override
        public void run() {
            final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new GamesDiffCallback(newGames, oldGames));
            handler.post(new Runnable() {
                @Override
                public void run() {
                    applyDiffResult(newGames, diffResult);
                }
            });
        }
    }).start();
}
 
Example #17
Source File: ColumnSortHandler.java    From TableView with MIT License 6 votes vote down vote up
private void swapItems(@NonNull List<ISortableModel> oldRowHeader,
                       @NonNull List<ISortableModel> newRowHeader,
                       @NonNull List<List<ISortableModel>> newColumnItems,
                       @NonNull SortState sortState
) {

    // Set new items without calling notifyCellDataSetChanged method of CellRecyclerViewAdapter
    mRowHeaderRecyclerViewAdapter.setItems(newRowHeader, !mEnableAnimation);
    mCellRecyclerViewAdapter.setItems(newColumnItems, !mEnableAnimation);

    if (mEnableAnimation) {
        // Find the differences between old cell items and new items.
        final RowHeaderSortCallback diffCallback = new RowHeaderSortCallback(oldRowHeader, newRowHeader);
        final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);

        diffResult.dispatchUpdatesTo(mRowHeaderRecyclerViewAdapter);
        diffResult.dispatchUpdatesTo(mCellRecyclerViewAdapter);
    }

    for (ColumnSortStateChangedListener listener : columnSortStateChangedListeners) {
        listener.onRowHeaderSortStatusChanged(sortState);
    }
}
 
Example #18
Source File: FirestorePagingOptions.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
private FirestorePagingOptions(@NonNull LiveData<PagedList<DocumentSnapshot>> data,
                               @NonNull SnapshotParser<T> parser,
                               @NonNull DiffUtil.ItemCallback<DocumentSnapshot> diffCallback,
                               @Nullable LifecycleOwner owner) {
    mData = data;
    mParser = parser;
    mDiffCallback = diffCallback;
    mOwner = owner;
}
 
Example #19
Source File: DiffResult.java    From epoxy with Apache License 2.0 5 votes vote down vote up
private DiffResult(
    @NonNull List<? extends EpoxyModel<?>> previousModels,
    @NonNull List<? extends EpoxyModel<?>> newModels,
    @Nullable DiffUtil.DiffResult differResult
) {
  this.previousModels = previousModels;
  this.newModels = newModels;
  this.differResult = differResult;
}
 
Example #20
Source File: DatabasePagingOptions.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
private DatabasePagingOptions(@NonNull LiveData<PagedList<DataSnapshot>> data,
                              @NonNull SnapshotParser<T> parser,
                              @NonNull DiffUtil.ItemCallback<DataSnapshot> diffCallback,
                              @Nullable LifecycleOwner owner) {
    mParser = parser;
    mData = data;
    mDiffCallback = diffCallback;
    mOwner = owner;
}
 
Example #21
Source File: ListAdapter.java    From Carbon with Apache License 2.0 5 votes vote down vote up
public void setItems(@NonNull List<I> items) {
    List<I> newItems = new ArrayList<>(items);
    if (!diff) {
        this.items = newItems;
        return;
    }
    if (diffCallback == null)
        diffCallback = new DiffListCallback<>();
    diffCallback.setLists(this.items, newItems);
    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);
    this.items = newItems;
    diffResult.dispatchUpdatesTo(this);
    setSelectionMode(selectionMode);
}
 
Example #22
Source File: ArrayAdapter.java    From Carbon with Apache License 2.0 5 votes vote down vote up
public void setItems(@NonNull I[] items) {
    I[] newItems = Arrays.copyOf(items, items.length);
    if (!diff) {
        this.items = newItems;
        return;
    }
    if (diffCallback == null)
        diffCallback = new DiffArrayCallback<>();
    diffCallback.setArrays(this.items, newItems);
    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);
    this.items = newItems;
    diffResult.dispatchUpdatesTo(this);
    setSelectedItems(selectedItems);
}
 
Example #23
Source File: ItemProvider.java    From AdapterDelegates with Apache License 2.0 5 votes vote down vote up
public Pair<List<Item>, DiffUtil.DiffResult> add() {
    List<Item> newlist = copyCurrent();

    newlist.add(2, newItem());
    newlist.add(4, newItem());

    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new ItemDiff(currentList, newlist));

    currentList = newlist;
    return Pair.create(newlist, diffResult);
}
 
Example #24
Source File: RVRendererAdapter.java    From Renderers with Apache License 2.0 5 votes vote down vote up
/**
 * Provides a ready to use diff update for our adapter based on the implementation of the
 * standard equals method from Object.
 *
 * @param newList to refresh our content
 */
public void diffUpdate(List<T> newList) {
  if (getCollection().size() == 0) {
    addAll(newList);
    notifyDataSetChanged();
  } else {
    DiffCallback diffCallback = new DiffCallback(collection, newList);
    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);
    clear();
    addAll(newList);
    diffResult.dispatchUpdatesTo(this);
  }
}
 
Example #25
Source File: StatisticActivity.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
public void update() {
    saveOldState();
    adapter.update();
    int start = layoutManager.findFirstVisibleItemPosition();
    int end = layoutManager.findLastVisibleItemPosition();
    long scrollToItemId = RecyclerView.NO_ID;
    int offset = 0;
    for (int i = start; i <= end; i++) {
        if (adapter.getItemId(i) != RecyclerView.NO_ID) {
            View v = layoutManager.findViewByPosition(i);
            if (v != null) {
                scrollToItemId = adapter.getItemId(i);
                offset = v.getTop();
                break;
            }
        }
    }
    DiffUtil.calculateDiff(this).dispatchUpdatesTo(adapter);
    if (scrollToItemId != RecyclerView.NO_ID) {
        int position = -1;

        for (int i = 0; i < adapter.getItemCount(); i++) {
            if (adapter.getItemId(i) == scrollToItemId) {
                position = i;
                break;
            }
        }
        if (position > 0) {
            layoutManager.scrollToPositionWithOffset(position, offset);
        }
    }
}
 
Example #26
Source File: SpendingRecyclerViewAdapter.java    From Moneycim with MIT License 5 votes vote down vote up
public void updateItems(List<Spending> spendings){
    final SpendingDiffCallback diffCallback = new SpendingDiffCallback(this.spendings, spendings);
    final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);

    this.spendings.clear();
    this.spendings.addAll(spendings);
    diffResult.dispatchUpdatesTo(this);
}
 
Example #27
Source File: GamesAdapter.java    From UpdogFarmer with GNU General Public License v3.0 5 votes vote down vote up
private void dispatchUpdates(List<Game> games, DiffUtil.DiffResult diffResult) {
    diffResult.dispatchUpdatesTo(new GamesListUpdateCallback(this, headerEnabled));
    dataSet.clear();
    dataSet.addAll(games);
    if (updateListener != null) {
        updateListener.onGamesListUpdated();
    }
}
 
Example #28
Source File: GamesAdapter.java    From UpdogFarmer with GNU General Public License v3.0 5 votes vote down vote up
private void applyDiffResult(List<Game> games, DiffUtil.DiffResult diffResult) {
    pendingUpdates.remove(games);
    dispatchUpdates(games, diffResult);
    if (pendingUpdates.size() > 0) {
        final List<Game> latest = pendingUpdates.pop();
        pendingUpdates.clear();
        updateDataInternal(latest);
    }
}
 
Example #29
Source File: BreadcrumbsView.java    From BreadcrumbsView with MIT License 5 votes vote down vote up
/**
 * Set breadcrumb items list and animates them correctly with recyclerview diff
 *
 * @param items Target list
 */
public <E extends IBreadcrumbItem> void updateItems(@NonNull List<E> items) {
	DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new BreadcrumbsDiffCallback((List<IBreadcrumbItem>)items, mAdapter.getItems()));
	mAdapter.setItems(items);
	diffResult.dispatchUpdatesTo(mAdapter);
	postScroll(-1, 0);
}
 
Example #30
Source File: AnimationDiffUtilsActivity.java    From AdapterDelegates with Apache License 2.0 5 votes vote down vote up
private void removeItems() {
    Pair<List<Item>, DiffUtil.DiffResult> remove = itemProvider.remove();
    if (remove == null) {
        Toast.makeText(this,
                "Can't remove items because min list size is required. Please add some items before removing",
                Toast.LENGTH_LONG).show();
    } else {
        adapter.setItems(remove.first);
        remove.second.dispatchUpdatesTo(adapter);
    }
}