Java Code Examples for androidx.recyclerview.widget.DiffUtil#calculateDiff()

The following examples show how to use androidx.recyclerview.widget.DiffUtil#calculateDiff() . 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
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 2
Source File: RecyclerViewListFragment.java    From android-app with GNU General Public License v3.0 6 votes vote down vote up
protected void resetContent() {
    List<T> items = getItems(0);

    boolean scrollToTop = false;
    if (recyclerViewLayoutManager != null) {
        scrollToTop = recyclerViewLayoutManager.findFirstCompletelyVisibleItemPosition() == 0;
    }

    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(getDiffUtilCallback(itemList, items));

    itemList.clear();
    itemList.addAll(items);

    diffResult.dispatchUpdatesTo(listAdapter);

    if (scrollListener != null) scrollListener.resetState();

    if (scrollToTop && recyclerView != null) {
        recyclerView.scrollToPosition(0);
    }
}
 
Example 3
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 4
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 5
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 6
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 7
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 8
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 9
Source File: ManageArticleTagsActivity.java    From android-app with GNU General Public License v3.0 5 votes vote down vote up
private void updateSuggestedTagList() {
    List<Tag> filteredList = filterTagList(currentText, availableTags, currentTags);

    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(
            new TagListFragment.TagListDiffCallback(suggestedTags, filteredList));

    suggestedTags.clear();
    suggestedTags.addAll(filteredList);

    diffResult.dispatchUpdatesTo(suggestedTagsAdapter);

    if (suggestedTagsView != null) {
        suggestedTagsView.setVisibility(suggestedTags.isEmpty() ? View.GONE : View.VISIBLE);
    }
}
 
Example 10
Source File: PositionFragment.java    From shinny-futures-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void refreshTD() {
    try {
        if (mView == null)return;
        if (!mIsUpdate) return;
        UserEntity userEntity = sDataManager.getTradeBean().getUsers().get(sDataManager.USER_ID);
        if (userEntity == null) return;
        mNewData.clear();

        for (PositionEntity positionEntity :
                userEntity.getPositions().values()) {

            int volume_long = Integer.parseInt(positionEntity.getVolume_long());
            int volume_short = Integer.parseInt(positionEntity.getVolume_short());
            if (volume_long != 0 && volume_short != 0) {
                PositionEntity positionEntityLong = positionEntity.cloneLong();
                PositionEntity positionEntityShort = positionEntity.cloneShort();
                mNewData.add(positionEntityLong);
                mNewData.add(positionEntityShort);
            } else if (!(volume_long == 0 && volume_short == 0)) {
                mNewData.add(CloneUtils.clone(positionEntity));
            }
        }

        if (mIsInAccountFragment && mNewData.isEmpty())
            mBinding.seeMd.setVisibility(View.VISIBLE);
        else mBinding.seeMd.setVisibility(View.GONE);

        Collections.sort(mNewData);
        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new PositionDiffCallback(mOldData, mNewData), false);
        mAdapter.setData(mNewData);
        diffResult.dispatchUpdatesTo(mAdapter);
        mOldData.clear();
        mOldData.addAll(mNewData);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 11
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 12
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 13
Source File: GroupMemberListAdapter.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
void updateData(@NonNull List<? extends GroupMemberEntry> recipients) {
  if (data.isEmpty()) {
    data.addAll(recipients);
    notifyDataSetChanged();
  } else {
    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffCallback(data, recipients));
    data.clear();
    data.addAll(recipients);
    diffResult.dispatchUpdatesTo(this);
  }
}
 
Example 14
Source File: ItemProvider.java    From AdapterDelegates with Apache License 2.0 5 votes vote down vote up
public Pair<List<Item>, DiffUtil.DiffResult> move() {
    List<Item> newlist = copyCurrent();

    Item c2 = newlist.remove(5);
    c2.color = color();
    newlist.add(1, c2);

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

    currentList = newlist;
    return Pair.create(newlist, diffResult);
}
 
Example 15
Source File: RecyclerAdapter.java    From StickyHeaders with Apache License 2.0 4 votes vote down vote up
void setData(List<Item> items) {
    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new SimpleDiffCallback(data, items));
    data.clear();
    data.addAll(items);
    diffResult.dispatchUpdatesTo(this);
}
 
Example 16
Source File: DataSetDetailAdapter.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void setDataSets(List<DataSetDetailModel> dataSets){
    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DataSetDiffCallback(this.dataSets, dataSets));
    this.dataSets.clear();
    this.dataSets.addAll(dataSets);
    diffResult.dispatchUpdatesTo(this);
}
 
Example 17
Source File: ContactOverviewSelectionAdapter.java    From natrium-android-wallet with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void updateList(List<Contact> newList) {
    List<Contact> oldList = this.contactList;
    this.contactList = newList;
    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new ContactSelectionDiffCallback(oldList, newList), false);
    diffResult.dispatchUpdatesTo(this);
}
 
Example 18
Source File: GroupDiffUtilComparator.java    From FeatureAdapter with Apache License 2.0 4 votes vote down vote up
@Override
public Object getChangePayload(List<ViewItem> oldItems, List<ViewItem> newItems) {
  final DiffUtilCallback callback = new DiffUtilCallback(oldItems, newItems);
  return DiffUtil.calculateDiff(callback, false);
}
 
Example 19
Source File: DataDiffSectionSpec.java    From litho with Apache License 2.0 4 votes vote down vote up
@OnDiff
public static <T> void onCreateChangeSet(
    SectionContext c,
    ChangeSet changeSet,
    @Prop Diff<List<? extends T>> data,
    @Prop(optional = true) @Nullable Diff<Boolean> detectMoves,
    @Prop(optional = true) @Nullable Diff<Boolean> alwaysDetectDuplicates) {

  final List<? extends T> previousData = data.getPrevious();
  final List<? extends T> nextData = data.getNext();
  final ComponentRenderer componentRenderer =
      new ComponentRenderer(DataDiffSection.getRenderEventHandler(c), c);
  final DiffSectionOperationExecutor operationExecutor =
      new DiffSectionOperationExecutor(changeSet);
  final RecyclerBinderUpdateCallback<T> updatesCallback;
  final boolean isTracing = ComponentsSystrace.isTracing();

  final Callback<T> callback = new Callback<>(c, data.getPrevious(), data.getNext());

  final ComponentsLogger logger = c.getLogger();
  final PerfEvent logEvent =
      logger == null
          ? null
          : LogTreePopulator.populatePerfEventFromLogger(
              c, logger, logger.newPerformanceEvent(c, EVENT_SECTIONS_DATA_DIFF_CALCULATE_DIFF));

  if (nextData != null && isDetectDuplicatesEnabled(alwaysDetectDuplicates)) {
    detectDuplicates(c, nextData, callback);
  }
  if (isTracing) {
    ComponentsSystrace.beginSection("DiffUtil.calculateDiff");
  }
  final DiffUtil.DiffResult result =
      DiffUtil.calculateDiff(callback, isDetectMovesEnabled(detectMoves));
  if (isTracing) {
    ComponentsSystrace.endSection();
  }

  if (logEvent != null) {
    logger.logPerfEvent(logEvent);
  }

  updatesCallback =
      new RecyclerBinderUpdateCallback<>(
          previousData, nextData, componentRenderer, operationExecutor);
  result.dispatchUpdatesTo(updatesCallback);

  updatesCallback.applyChangeset(c);
}
 
Example 20
Source File: RecyclerViewAdapterHelper.java    From MultiTypeRecyclerViewAdapter with Apache License 2.0 4 votes vote down vote up
/**
 * 核心部分,新老数据比较
 *
 * @param newData     新数据
 * @param newHeader   新头
 * @param level       数据类型等级
 * @param refreshType 刷新类型
 * @return DiffResult
 */
protected final DiffUtil.DiffResult handleRefresh(List<T> newData, T newHeader, T newFooter, int level, int refreshType) {
    if (refreshType == REFRESH_ALL) {
        return DiffUtil.calculateDiff(getDiffCallBack(mData, newData), isDetectMoves());
    }

    checkStandardMode();

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

    LevelData<T> oldLevelData = mLevelData.get(level);
    List<T> data = null;
    T header = null;
    T footer = null;
    boolean isRefreshData = (refreshType & REFRESH_DATA) == REFRESH_DATA;
    boolean isRefreshHeader = (refreshType & REFRESH_HEADER) == REFRESH_HEADER;
    boolean isRefreshFooter = (refreshType & REFRESH_FOOTER) == REFRESH_FOOTER;

    if (oldLevelData != null) {
        List<T> oldItemData = oldLevelData.getData();
        if (oldItemData != null && !oldItemData.isEmpty()) {
            if (isRefreshData) {
                mNewData.removeAll(oldItemData);
            } else {
                data = oldItemData;
            }
        }

        T oldItemHeader = oldLevelData.getHeader();
        if (oldItemHeader != null) {
            if (isRefreshHeader) {
                mNewData.remove(oldItemHeader);
            } else {
                header = oldItemHeader;
            }
        }

        T oldItemFooter = oldLevelData.getFooter();
        if (oldItemFooter != null) {
            if (isRefreshFooter) {
                mNewData.remove(oldItemFooter);
            } else {
                footer = oldItemFooter;
            }
        }
    }

    int positionStart = getPositionStart(level);
    int dataSize = data == null ? 0 : data.size();

    if (!(newData == null || newData.isEmpty()) && isRefreshData) {
        data = newData;
        ResourcesManager.AttrEntity attrEntity = mResourcesManager.getAttrsEntity(level);
        if (!attrEntity.initState || data.size() <= attrEntity.minSize) {
            mNewData.addAll(header == null ? positionStart : positionStart + 1, data);
            dataSize = data.size();
        } else {
            mNewData.addAll(header == null ? positionStart : positionStart + 1, data.subList(0, attrEntity.minSize));
            dataSize = attrEntity.minSize;
        }
        attrEntity.isFolded = attrEntity.initState;
    }

    if (newHeader != null && isRefreshHeader) {
        header = newHeader;
        mNewData.add(positionStart, newHeader);
    }

    if (newFooter != null && isRefreshFooter) {
        footer = newFooter;
        if (header != null) {
            positionStart++;
        }
        positionStart += dataSize;
        mNewData.add(positionStart, footer);
    }
    DiffUtil.DiffResult result = DiffUtil.calculateDiff(getDiffCallBack(mData, mNewData), isDetectMoves());
    mLevelData.put(level, new LevelData<>(data, header, footer));
    return result;
}