android - 带有 SortedList 的 RecyclerView 显示重复项
问题描述
我在列表中使用SortedList
a 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,我也会在我的列表中看到:
解决方案
您比较GameListHeader.getDate()
两种不同方式的响应。在areContentsTheSame()
它的
return oldItem.getDate().equals(newItem.getDate());
在areItemsTheSame()
你使用
return item1.getDate() == item2.getDate();
尽管从您的帖子中不清楚如何getDate()
生成响应或数据类型是什么,但我确实认为其中之一是不正确的。如果getDate()
返回 aString
那么String.equals(String)
是您想要的并且==
不正确。
推荐阅读
- android - 当我们按下返回箭头时会运行什么函数?
- flask - 如何检查 url_for 是否引用现有文件?
- spring - Spring Interceptor Prehandle 如果发生错误,如何获取实际的 request.getServletPath() 而不是“错误”
- inheritance - 继承 jsonnet 库
- cordova - 如何隐藏/删除 Ionic 4 Cordova Windows 10 应用程序后退按钮?
- python - 在 Python 中打印具有相应值的数组索引
- excel - 如果数组包含某些文本(例如,如果 rRng(i,k) 包含“/2”),如何使用 select case 语句
- angular - Angular 7处理大型post http请求
- python - 如何在 JSONField 中找到最大/最小值?
- javascript - (WebGL)如何将顶点添加到已经初始化的顶点缓冲区?