问题描述
所以我有一个与RecyclerView
有关的活动,并且我想通过按活动中具有onClickListener()
的按钮来更改RecyclerView
中每个项目的TextView
.
So I have an activity with RecyclerView
and I want to change TextView
of every item in the RecyclerView
by pressing button that has onClickListener()
in the activity.
我想知道在性能方面哪个更好:
I'm wondering what is better in terms of performance:
- 使用
notifyDataSetChanged
个. - 使用条件为int i的循环小于
List.size()
,其中notifyItemChanged
将被调用几次.
- Use
notifyDataSetChanged
ones. - Use loop with condition like int i is less than
List.size()
wherenotifyItemChanged
would be called few times.
在这两种情况下,我都在RecyclerView
适配器中创建布尔变量,onBindViewHolder
使用该变量来了解如何更新项目.默认情况下为false,在单击按钮后变为true,因此onBindViewHolder
以不同的方式更新项目.
In both cases I create boolean variable in RecyclerView
Adapter which is used by onBindViewHolder
to know how to update item. By default it's false and after button click it becomes true so onBindViewHolder
updates item in different way.
我也想知道这种方法是否完全合适.
Also I would like to know if this approach is suitable at all.
推荐答案
如果仅更新视图的一部分,请使用notifyItemRangeChanged()
或notifyItemChanged()
而不是notifiyDataSetChanged()
.这里的差异与结构更改与项目更改有关.这是在RecyclerView.Adapter文档上" >这里.
If you are simply updating one part of the view, use the notifyItemRangeChanged()
or notifyItemChanged()
instead of notifiyDataSetChanged()
. The difference here has to do with structural changes vs item changes. This is on the android developers RecyclerView.Adapter
documentation found here.
这是有关两种类型更改之间差异的另一个提示:
Here is another tidbit on the differences between the two types of changes:
此内容取自上述页面
因此,为了澄清使用notifyDataSetChanged()
作为最后手段,而是问问自己是否可以执行以下一种方法,以及是否可以代替使用:
So just to clarify use notifyDataSetChanged()
as a last resort, and instead ask yourself if you can preform one of these methods instead, and if you can use it instead:
notifyItemChanged(int)
notifyItemInserted(int)
notifyItemRemoved(int)
notifyItemRangeChanged(int, int)
notifyItemRangeInserted(int, int)
notifyItemRangeRemoved(int, int)
之所以有意义,是因为notifyDataSetChanged()
会在很大程度上尝试根据数据重绘所有内容,而无需对其进行任何先前的假设,而其他方法只会寻找更改.这意味着适配器必须执行很多不必要的工作.这是notifyDataSetChanged()
的作用:
which makes sense because notifyDataSetChanged()
will pretty much try to redraw everything based on the data and make no previous assumptions on it, while the other methods will just look for changes. That means the adapter has to do a lot more work that is not necessary. This is what notifyDataSetChanged()
does:
使用增量或范围方法也很有意义,因为要更改文本,您需要获取每个新文本,并且在执行此操作时,应该告诉适配器已对其进行了更改.现在,如果您单击按钮,则获取所有新的文本值,并创建新列表或其他内容,然后调用沉重的notifyDataSetChanged()
.
This also makes sense to use the incremental or range approach, because you are changing the text, you need to go get each new text and when you do that you should tell the adapter you changed it. Now, if you do a button click and get all new text values, and create a new list or something then call heavy notifyDataSetChanged()
.
这篇关于有什么更好的? notifyDataSetChanged或notifyItemChanged在循环中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!