从RecyclerView适配器检查以下逻辑。有什么不对的吗?

时间:2015-12-21 17:51:40

标签: collections android-recyclerview

我尽可能多地替换项目,然后根据条件添加或删除项目。

public void addFileListEntries(List<FileListEntry> fileListEntries) {
    for (int i = 0; i < Math.min(mFileListEntries.size(), fileListEntries.size()); i++) {
        mFileListEntries.set(i, fileListEntries.get(i));
        notifyItemChanged(i);
    }
    if (mFileListEntries.size() > fileListEntries.size()) {
        ArrayList<FileListEntry> subList = new ArrayList<>(mFileListEntries
                .subList(fileListEntries.size(), mFileListEntries.size() - 1));
        mFileListEntries.removeAll(subList);
        notifyItemRangeRemoved(fileListEntries.size(),
                fileListEntries.size() + subList.size() - 1);
    } else if (mFileListEntries.size() < fileListEntries.size()) {
        ArrayList<FileListEntry> subList = new ArrayList<>(fileListEntries
                .subList(mFileListEntries.size(), fileListEntries.size() - 1));
        mFileListEntries.addAll(subList);
        notifyItemRangeInserted(mFileListEntries.size(),
                mFileListEntries.size() + subList.size() - 1);
    }
}

此处mFileListEntries是adpter的DataSet,而fileListEntries是新的DataSet。

1 个答案:

答案 0 :(得分:0)

我想Android中的customTasksDataGrid.ItemsSource = model; customTasksDataGrid.Items.SortDescriptions.Add(new SortDescription("DueDate", ListSortDirection.Ascending)); 实现默认会有效地处理这个问题。您只需将RecyclerView分配给fileListEntries并调用mFileListEntries(在主要主题中)。如果您不想更改notifyDataSetChanged对象,请在调用mFileListEntries之前将其清除并addAll fileListEntries

事实上,您第一次多次调用notifyDataSetChanged可能会造成更多伤害。仅当您知道添加/删除/更改的项目的确切子集时,才会使用notifyItemChangednotifyItemChangednotifyItemRangeRemoved