notifyDataSetChanged 示例 [英] notifyDataSetChanged example
问题描述
我正在尝试在我的 Android 应用程序
中使用 notifyDataSetChanged()
方法用于 ArrayAdapter
但它对我不起作用.
I'm trying to use in my Android Application
the notifyDataSetChanged()
method for an ArrayAdapter
but it doesn't work for me.
我发现作为这里的答案,notifyDataSetChanged()
应该在主线程,但没有示例.
I found as answer here, that notifyDataSetChanged()
should run in the main thread, but there was no example for that.
任何人都可以发送一个示例或至少一个链接吗?!
Could anybody send an example or at least a link?!
推荐答案
对于 ArrayAdapter
,notifyDataSetChanged
仅在使用 add()
时有效适配器上的 code>、insert()
、remove()
和 clear()
.
For an ArrayAdapter
, notifyDataSetChanged
only works if you use the add()
, insert()
, remove()
, and clear()
on the Adapter.
当一个 ArrayAdapter
被构造时,它保存了对传入的 List
的引用.如果你要传入一个 List
这是一个 Activity 的成员,稍后更改该 Activity 成员,ArrayAdapter
仍然持有对原始 List
的引用.适配器不知道您更改了活动中的 List
.
When an ArrayAdapter
is constructed, it holds the reference for the List
that was passed in. If you were to pass in a List
that was a member of an Activity, and change that Activity member later, the ArrayAdapter
is still holding a reference to the original List
. The Adapter does not know you changed the List
in the Activity.
您的选择是:
- 使用
ArrayAdapter
的函数修改底层List(add()
,insert()
,remove()
、clear()
等) - 使用新的
List
数据重新创建ArrayAdapter
.(使用大量资源和垃圾收集.) - 创建您自己的从
BaseAdapter
和ListAdapter
派生的类,允许更改底层的List
数据结构. - 每次更新列表时使用
notifyDataSetChanged()
.要在 UI 线程上调用它,请使用Activity
的runOnUiThread()
.然后,notifyDataSetChanged()
将起作用.
- Use the functions of the
ArrayAdapter
to modify the underlying List (add()
,insert()
,remove()
,clear()
, etc.) - Re-create the
ArrayAdapter
with the newList
data. (Uses a lot of resources and garbage collection.) - Create your own class derived from
BaseAdapter
andListAdapter
that allows changing of the underlyingList
data structure. - Use the
notifyDataSetChanged()
every time the list is updated. To call it on the UI-Thread, use therunOnUiThread()
ofActivity
. Then,notifyDataSetChanged()
will work.
这篇关于notifyDataSetChanged 示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!