android - 回收站 View : notify item inserted messes up the whole list

标签 android android-recyclerview notifydatasetchanged

我有一个 recyclerview 最初有 5 个项目。现在我要做的是在位置 0、1、2、3 和 4 处添加另外 5 个项目。所以我这样做:

         //add another 5 items to my recyclerview

         for(int i=0 , i < 5 , i++){
          //add new item to the list at the specified position
          my_list.add(i , "new item"+ String.valueOf(i));

          //notify adapter

          my_adapter.notifyItemInserted(i);

         }

问题是调用 (notifyItemInserted(i)) 弄乱了整个列表。但是调用 notifyAdapterDataSetChanged() 不会弄乱任何东西。

我想避免调用 notifyAdapterDataSetChanged()。

为什么会这样?

谢谢。

编辑

我会更新问题以便其他人理解问题:

我最初在 0,1,2,3,4 位置有 5 个项目,现在我想在 0,1,2,3,4 位置的前 5 个项目中添加 5 个新项目(我希望新项目取代之前的)如何正确地通知适配器?

最佳答案

First i appreciate :) you to use method notifyItemInsert() because it will give you some inserting animation without any effort and will never hang up your view even hundreds of items in list when notifying. I have seen many developers using notifyDataSetChange that works well with small list. But if your api does not support paging and you got hundreds in list then your view will stuck for a while when setting adapter.

如果您想更改现有项目。

for(int i=0 , i < 5 , i++){
  my_list.set(i , "new item"+ String.valueOf(i));
}

my_adapter.notifyItemRangeChanged(0, 5); 

您还可以使用 notifyItemChanged(list.size() - 1);,如下所示。

如果要插入新的

for (int i = 0; i < 5; i++) {
            list.add("new item" + String.valueOf(i));
            notifyItemInserted(list.size() - 1);
        }

现在明白了——首先你不知道列表中已经有多少项,所以不要使用 my_list.add(i , "new item"+ String.valueOf(i)); 因为这会替换旧项,第二次使用 notifyItemInserted(list.size() - 1);,它会自动检查插入了哪个项。

您还可以使用 Hed 的 notifyItemRangeInserted。这也是对的

更新:你可以这样做。首先在现有列表中添加您的 5 项列表。然后将最终列表设置为适配器。

ArrayList arrayList5Items;
ArrayList arrayList = my_adapter.getList();
arrayList5Items.addAll(arrayList);
my_list = arrayList5Items;
my_adapter.notifyItemRangeInserted(0, 5);

关于android - 回收站 View : notify item inserted messes up the whole list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49839709/

相关文章:

java - 将字符串发送到 RecyclerViewHolder 中的 onClick

java - 从另一个 Activity 更新 Listview 可见 View (行)

android - Unity - Google Play 游戏服务实时多人游戏关闭 WaitingRoomUI() 方法?

java - 在Android应用程序中存储用户设置的最合适方法是什么

android - 无法解决:com.android.support:cardview-v7:26.0.0 android

android - FragmentPagerAdapter notifyDataSetChanged 不起作用

android - 未调用 NotifyDataSetChanged

android - SeekBar DataBinding 表达式上的资源 NotFoundException

android - 当用户从 flutter 的设置屏幕导航回应用程序时检测方法

java - RecyclerView 中 MapView 的 IndexOutOfBoundsException