我有一个显示 CardView 列表的 RecyclerView。我最近将项目从使用 RecyclerView 适配器切换到使用 AsyncListDiffer 适配器以利用后台线程上的适配器更新。我已经转换了列表的所有以前的 CRUD 和过滤方法,但无法使排序方法正常工作。
我有不同类型或类别的 CardView,我想按类型/类别进行排序。我克隆了现有列表 mCards,因此“幕后”DiffUtil 将其视为与我想要排序的现有列表不同的列表。然后我使用 AsynListDiffer 的 submitList()。
该列表未排序。我在这里想念什么?
主要活动:
private static List<Card> mCards = null;
...
mCardViewModel = new ViewModelProvider(this).get(CardViewModel.class);
mCardViewModel.getAllCards().observe(this,(cards -> {
mCards = cards;
cardsAdapter.submitList(mCards);
}));
mRecyclerView.setAdapter(cardsAdapter);
A click on a "Sort" TextView runs the following code:
ArrayList<Card> sortItems = new ArrayList<>();
for (Card card : mCards) {
sortItems.add(card.clone());
}
Collections.sort(sortItems, new Comparator<Card>() {
@Override
public int compare(Card cardFirst, Card cardSecond) {
return cardFirst.getType().compareTo(cardSecond.getType());
}
});
cardsAdapter.submitList(sortItems);
// mRecyclerView.setAdapter(cardsAdapter); // Adding this did not help
AsyncListDifferAdapter:
public AsyncListDifferAdapter(Context context) {
this.mListItems = new AsyncListDiffer<>(this, DIFF_CALLBACK);
this.mContext = context;
this.mInflater = LayoutInflater.from(mContext);
}
public void submitList(List<Quickcard> list) {
if (list != null) {
mListItems.submitList(list);
}
}
public static final DiffUtil.ItemCallback<Card> DIFF_CALLBACK
= new DiffUtil.ItemCallback<Card>() {
@Override
public boolean areItemsTheSame(@NonNull Card oldItem, @NonNull Card newItem) {
// User properties may have changed if reloaded from the DB, but ID is fixed
return oldItem.getId() == newItem.getId();
}
@Override
public boolean areContentsTheSame(@NonNull Card oldItem, @NonNull Card newItem) {
return oldItem.equals(newItem);
}
@Nullable
@Override
public Object getChangePayload(@NonNull Card oldItem, @NonNull Card newItem) {
return super.getChangePayload(oldItem, newItem);
}
};
模型:
@Entity(tableName = "cards")
public class Card implements Parcelable, Cloneable {
// Parcelable code not shown for brevity
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "cardId")
public int id;
@ColumnInfo(name = "cardType")
private String type;
@Ignore
public Card(int id, String type) {
this.id = id;
this.type = type;
}
public int getId() {
return this.id;
}
public String getType() {
return this.type;
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
else if (obj instanceof Card) {
Card card = (Card) obj;
return id == card.getId() &&
type.equals(card.getType());
} else {
return false;
}
}
@NonNull
@Override
public Card clone() {
Card clone;
try {
clone = (Card) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
return clone;
}