首页 > 解决方案 > 如何对每个新项目的 RecyclerView 进行排序?

问题描述

我有一个 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);
   }
} 

标签: androidandroid-recyclerview

解决方案


可以通过使用实现接口或创建实现ItemPTERM的接口来定义 s之间的顺序关系来完成。Comparable<ItemPTERM>ItemPTERMComparatorComparator<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);
   }
}

推荐阅读