android - 如何对每个新项目的 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);
}
}
解决方案
可以通过使用实现接口或创建实现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);
}
}
推荐阅读
- macros - Racket - 是否可以在单个文件中定义和使用相同的语言?
- html - Flex:使孩子具有相同高度的绝对兄弟姐妹
- tfs - 如何使用 Web 代理配置 TFS 构建代理
- css - 未应用 CSS 变量
- java - 如何从接受泛型枚举的方法返回泛型枚举?
- python - 在 Pandas 数据框中显示字符串
- spring-boot - ServletRequestParameter 异常,参数不存在
- ssas - 在 SQL 探查器中设置什么来调查 SSAS 多维数据集同步作业挂起?
- python - 即使使用 Dropout、L2 和更多数据,验证准确度(LeNet-5)也没有提高
- azure - 差异 - 非典型旅行、不可能旅行、不熟悉的登录