簡體   English   中英

如何對每個新項目的 RecyclerView 進行排序?

[英]How to sort the RecyclerView on each new item?

我有一個 RecyclerView,我從另一個 RecyclerView 添加項目,每個項目都有一個名為“TYPE”的屬性,它的值可以是“FASE1”、“FASE2”和“FASE8”。

當新項目添加到該列表或刪除時,我需要根據 TYPE 值對其進行排序。

所以所有項目都必須像 ITEM1 FASE1 > ITEM2 FASE2 ....

到目前為止,我只是在 RecyclerView 中添加或刪除項目,如下所示:

這是來自 RecyclerView 的 RecyclerView Adapter 的代碼,它將項目添加到另一個 RecyclerView。

private void addOrRemove(int position, boolean add) {
        // piattiItems is a reference to ArrayList<ItemPTERM> from the Adapter of the RecyclerView where i have to add the items
        Item prodotto = mFilteredList.get(position); // getting item from current RecyclerView
        ItemPTERM prodottoAggiunto = piattiAdapter.getItemByCode(prodotto.getCodice()); // cheking if there is yet the same item in the RecyclerView where i have to add it
   if (add) {
        piattiItems.add(nuovoProdotto(prodotto)); // adding new item
        piattiAdapter.notifyItemInserted(size);
        recyclerPiatti.scrollToPosition(size);
   }else {
        piattiItems.remove(prodottoAggiunto); // removing item
        piattiAdapter.notifyItemRemoved(position);
   }
} 

它可以通過定義之間的一個順序關系來完成ItemPTERM通過實現S中的Comparable<ItemPTERM>接口與ItemPTERM或通過創建一個Comparator ,它實現Comparator<ItemPTERM>

在后者中,您應該實現compare方法。 我假設“TYPE”是一個讓事情更簡單的Enum 順便說一下,如果它是一個String你應該為你的目標實現一個特定的算法。

comparator准備好時,您可以像往常一樣向piattiItems添加元素並調用Collections.sort(piattiItems, comparator)ArrayList進行排序。 現在您可以獲取新添加項的索引並使用它來告訴您的RecyclerView該項的位置。 RecyclerView將通過在正確的位置顯示項目來完成剩下的工作!

private Comparator<ItemPTERM> mComparator = new Comparator<>(){
    @Override
    public int compare(ItemPTERM o1, ItemPTERM o2) {
        return o1.type.compareTo(o2.type); // supposing that type is enum
    }
}

private void addOrRemove(int position, boolean add) {
        Item prodotto = mFilteredList.get(position);
        ItemPTERM prodottoAggiunto = piattiAdapter.getItemByCode(prodotto.getCodice());
   if (add) {
        ItemPTERM newItem = nuovoProdotto(prodotto);
        piattiItems.add(newItem);
        Collections.sort(piattiItems, mComparator); // sorts after adding new element
        int index = piattiItems.indexOf(newItem); // gets the index of the newly added item
        piattiAdapter.notifyItemInserted(index); // uses the index to tell the position to the RecyclerView
        recyclerPiatti.scrollToPosition(index);
   }else {
        piattiItems.remove(prodottoAggiunto);
        piattiAdapter.notifyItemRemoved(position);
   }
}

這個想法是:

  1. RecyclerView應該只負責顯示您的數據,它不應該知道您的List數據的順序。

  2. 您的List數據應該負責訂單。


因此,在向RecylerView添加新項目后,首先更新/調整您的List ,然后在Adapter對象上調用notifyDataSetChanged() 或者,如果您將ListAdapterDiffUtil ListAdapter使用,則只需調用sumitList() ,它只會更新更改的項目,而不是像RecyclerView.Adapter那樣更新整個List

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM