在列表视图中重绘单行 [英] Redraw a single row in a listview
问题描述
是否可以在 ListView
中重绘单行?我有一个 ListView
,其中的行是 LinearLayout
.我听取了偏好更改,有时我只需要更改一行的 LinearLayout
内的一个 View
.有没有办法让它在不调用 listview.notifyDatasetChanged()
的情况下重绘该行?
Is it possible to redraw a single row in a ListView
? I have a ListView
with rows that are LinearLayout
s. I listen to a preference change and sometimes I need to change just one View
inside the LinearLayout
of a single row. Is there a way to make it redraw that row without calling listview.notifyDatasetChanged()
?
我尝试在视图上调用 view.invalidate()(在 LinearLayout
内),但它没有重绘该行.
I've tried calling view.invalidate() on the view (inside the LinearLayout
) but it doesn't redraw the row.
推荐答案
As Romain Guy 解释了一会儿 在 Google I/O 会议期间返回,仅更新列表视图中的一个视图的最有效方法如下(此方法更新整个 View
数据):
As Romain Guy explained a while back during the Google I/O session, the most efficient way to only update one view in a list view is something like the following (this one update the whole View
data):
ListView list = getListView();
int start = list.getFirstVisiblePosition();
for(int i=start, j=list.getLastVisiblePosition();i<=j;i++)
if(target==list.getItemAtPosition(i)){
View view = list.getChildAt(i-start);
list.getAdapter().getView(i, view, list);
break;
}
假设 target
是适配器的一项.
Assuming target
is one item of the adapter.
此代码检索ListView
,然后浏览当前显示的视图,将您要查找的target
项与每个显示的视图项进行比较,如果您的目标在这些,获取封闭视图并在该视图上执行适配器 getView()
以刷新显示.
This code retrieve the ListView
, then browse the currently shown views, compare the target
item you are looking for with each displayed view items, and if your target is among those, get the enclosing view and execute the adapter getView()
on that view to refresh the display.
附带说明 invalidate()
不像某些人期望的那样工作,也不会像 getView()
那样刷新视图,notifyDataSetChanged()
将重建整个列表并最终为每个显示的项目调用 getview()
并且 invalidateViews()
也会影响一堆.
As a side note invalidate()
doesn't work like some people expect and will not refresh the view like getView()
does, notifyDataSetChanged()
will rebuild the whole list and end up calling getview()
for every displayed items and invalidateViews()
will also affect a bunch.
最后一件事,如果他只需要更改行视图的子级而不是像 getView
那样更改整行,也可以获得额外的性能.在这种情况下,以下代码可以替换 list.getAdapter().getView(i, view, list);
(更改 TextView
文本的示例):
One last thing, one can also get extra performance if he only needs to change a child of a row view and not the whole row like getView
does. In that case, the following code can replace list.getAdapter().getView(i, view, list);
(example to change a TextView
text):
((TextView)view.findViewById(R.id.myid)).setText("some new text");
我们信任的代码.
这篇关于在列表视图中重绘单行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!