首页 > 解决方案 > 带有 SortedList 的 RecyclerView 显示重复项

问题描述

我在列表中使用SortedLista 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,我也会在我的列表中看到:

https://i.stack.imgur.com/vWYml.png

标签: androidlistviewandroid-recyclerviewsortedlist

解决方案


您比较GameListHeader.getDate()两种不同方式的响应。在areContentsTheSame()它的

return oldItem.getDate().equals(newItem.getDate());

areItemsTheSame()你使用

return item1.getDate() == item2.getDate();

尽管从您的帖子中不清楚如何getDate()生成响应或数据类型是什么,但我确实认为其中之一是不正确的。如果getDate()返回 aString那么String.equals(String)是您想要的并且==不正确。


推荐阅读