[英]Android change textview in recyclerview in all items without redrawing the entire list
I have a recyclerview with a list of items, and each item has, among other things, a textview with a distance from the user. 我有一个带有项目列表的recyclerview,每个项目除其他外还有一个与用户保持一定距离的textview。 As the user physically moves around I want to update the distances of the items without redrawing the list.
当用户身体四处走动时,我想更新项目的距离而不重绘列表。 For example, assume the user is standing in the middle of a triangle with the points being item1,2,3:
例如,假设用户站在三角形的中间,点为item1,2,3:
item1 5 feet item1 5英尺
item2 10 feet item2 10英尺
item3 15 feet item3 15英尺
now the user moves 2 feet towards item1 - so it changes to: 现在,用户将2英尺移向了item1-因此更改为:
item1 3 feet item1 3英尺
item2 12 feet item2 12英尺
item3 17 feet item3 17英尺
but I don't want a redraw. 但我不想重画。 In other words, if the list has 5000 items and the user has scrolled down to item 3150 and then changed his location, I don't want to do something like notifydatasetchanged which will then redraw the entire list and show the user everything from position 0. I want to instead dynamically change only the text for the distance for every item in the list and, as far as the user is concerned, everything is the same and only the distances have changed.
换句话说,如果列表中有5000个项目,并且用户向下滚动到项目3150,然后更改了他的位置,则我不想执行诸如notifydatasetchanged之类的操作,该操作将重绘整个列表并向用户显示位置0的所有内容我想改为动态地仅更改列表中每个项目的距离的文本,并且就用户而言,一切都相同,并且只有距离发生了变化。
What is the best way of doing this? 最好的方法是什么?
First of all, you cannot ovoid list redraw, that is just how it works to update UI but rest assured, there are caches all around to handle small changes. 首先,您不能避免列表重绘,这就是更新UI的方式,但是请放心,到处都有缓存来处理小的更改。
About items, if you call notifyDataSetChanged
RecyclerView will rebind only visible views. 关于项目,如果您调用
notifyDataSetChanged
,则RecyclerView将仅重新绑定可见视图。 So that will be the cost you are paying, the actual size of the adapter (5000 in your example) is irrelevant. 因此,这就是您要支付的费用,适配器的实际大小(在示例中为5000)无关紧要。
If you want RecyclerView to update only changed views, you have to call notifyItemChanged(position)
. 如果您希望RecyclerView仅更新更改的视图,则必须调用
notifyItemChanged(position)
。 In that case, RecyclerView will rebind only changed items and only if they are visible. 在这种情况下,RecyclerView将仅在更改的项目可见的情况下重新绑定它们。
If you have stable ids, even if you call notifyDataSetChanged
, if your adapter has stable ids, RecyclerView will call onBindViewHolder
with the existing view holder that currently represents the item at that position. 如果您具有稳定的ID,则即使您调用
notifyDataSetChanged
,如果适配器具有稳定的ID,RecyclerView也会使用当前表示该项目的现有视图保持器来调用onBindViewHolder
。 Keep a reference to your item in the ViewHolder. 在ViewHolder中保留对您的项目的引用。 When
onBind
is called, check if it is the same item and only update necessary parts. 调用
onBind
,请检查是否相同,并且仅更新必要的部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.