【发布时间】:2018-07-01 21:14:05
【问题描述】:
我在列表中使用SortedList 和RecyclerViewAdapter。因此,我通过侦听器将我的项目(从后台线程中的后端加载)发送到我的GameListAdapter。根据我的SortedListAdapterCallback 中实现的逻辑,发送到具有相同id 的适配器的项目应该被替换而不是被多次插入。不幸的是,这主要是,但并非总是如此。
这是我的GameListAdapter的构造函数
public GameListAdapter(RecyclerView list) {
this.list = list;
gamelistItems = new SortedList<>(GameListItem.class, new SortedListAdapterCallback<GameListItem>(this) {
@Override
public int compare(GameListItem o1, GameListItem o2) {
return o1.getDate().compareTo(o2.getDate());
}
@Override
public boolean areContentsTheSame(GameListItem oldItem, GameListItem newItem) {
if (oldItem instanceof GameListHeader && newItem instanceof GameListHeader) {
return oldItem.getDate().equals(newItem.getDate());
} else if (oldItem instanceof Game && newItem instanceof Game) {
Game gameOld = (Game) oldItem;
Game gameNew = (Game) newItem;
if (gameOld.getId() != gameNew.getId()) {
return false;
}
if (!gameOld.getTeamHome().equals(gameNew.getTeamHome())) {
return false;
}
if (!gameOld.getTeamAway().equals(gameNew.getTeamAway())) {
return false;
}
if (gameOld.getScoreHome() != gameNew.getScoreHome()) {
return false;
}
if (gameOld.getScoreAway() != gameNew.getScoreAway()) {
return false;
}
if (!gameOld.getState().equals(gameNew.getState())) {
return false;
}
return true;
}
return false;
}
@Override
public boolean areItemsTheSame(GameListItem item1, GameListItem item2) {
if (item1 instanceof GameListHeader && item2 instanceof GameListHeader) {
return item1.getDate() == item2.getDate();
} else if (item1 instanceof Game && item2 instanceof Game) {
return ((Game) item1).getId() == ((Game) item2).getId();
}
return false;
}
});
DataStorage.getInstance().registerListener(this);
}
通过此方法将项目添加到列表中:
@Override
public void onAddedGame(Game game) {
Handler handler = new Handler();
handler.post(() -> gamelistItems.add(game));
}
即使这些项目具有相同的 id,我在我的列表中也看到了这一点:
【问题讨论】:
标签: android listview android-recyclerview sortedlist