2012-02-21 76 views
13

我ArrayAdapter这个项目结构:安卓ArrayAdapter项目更新

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout ... > 

     <TextView 
      android:id="@+id/itemTextView" 
      ... /> 
</RelativeLayout> 

并添加此适配器,以便:

mAdapter = new ArrayAdapter<String>(this, R.layout.item, 
              R.id.itemTextView, itemsText); 

一切都很好,但我想更新适配器的项目文本。我发现一个解决方案

mAdapter.notifyDataSetChanged(); 

但不明白如何使用它。请帮助。

UPD 我的代码:

String[] itemsText = {"123", "345", "567"}; 
ArrayAdapter<String> mAdapter; 

的onCreate

mAdapter = new ArrayAdapter<String>(this, R.layout.roomitem, 
               R.id.itemTextView, itemsText); 
setListAdapter(mAdapter); 
itemsText = {"789", "910", "1011"}; 

的onClick

mAdapter.notifyDataSetChanged(); 
//it's dont work 

回答

34

我认为像这样

public void updatedData(List itemsArrayList) { 

    mAdapter.clear(); 

    if (itemsArrayList != null){ 

     for (Object object : itemsArrayList) { 

      mAdapter.insert(object, mAdapter.getCount()); 
     } 
    } 

    mAdapter.notifyDataSetChanged(); 

} 
+4

你不需要添加项目到适配器,只需调用notifyDataSetChanged一旦你对数组列表 – barry 2012-02-21 16:06:56

+1

完成的工作,我打电话notifyDataSetChanged但没有任何反应 – Leo 2012-02-21 16:13:31

+0

你做什么在onclick,或方法,其中u改变一些东西在itemsText中? – Luciano 2012-02-21 16:24:35

4

假设itemTexts为String数组或字符串的ArrayList,在其中添加新项目进入itemsTextat之后的时间你可以拨打

mAdapter.notifyDataSetChanged(); 

如果你没有得到答案,请放一些代码。

35

你的问题是指针的一个典型的Java错误。

第一步是创建一个数组并将该数组传递给适配器。

在第二步中,您将创建一个具有新信息的新数组(新指针被创建),但适配器仍然指向原始数组。

// init itemsText var and pass to the adapter 
String[] itemsText = {"123", "345", "567"}; 
mAdapter = new ArrayAdapter<String>(..., itemsText); 

//ERROR HERE: itemsText variable will point to a new array instance 
itemsText = {"789", "910", "1011"}; 

所以,你可以做两两件事,一,更新,而不是创建一个新的数组内容:

//This will work for your example 
items[0]="123"; 
items[1]="345"; 
items[2]="567"; 

...或者我会做什么,用一个列表,像:

List<String> items= new ArrayList<String>(3); 
boundedDevices.add("123"); 
boundedDevices.add("456"); 
boundedDevices.add("789"); 

而且在更新:

boundedDevices.set("789"); 
boundedDevices.set("910"); 
boundedDevices.set("1011"); 

要添加更多的信息,在实际应用中,通常你更新与服务或内容提供商的信息列表适配器的内容,因此通常更新你会做一些这样的项目:

​​

有了这个,你将清除旧的结果并加载新的结果(认为新的结果应该有不同数量的项目)。

并且当然在更新数据后致电notifyDataSetChanged();

如果您有任何疑问请不要犹豫,以发表评论。

+0

再来一次!非常好,很好地解释。 – Tim 2013-05-30 12:33:35

+0

我正在使用fragments.I做了以上所有步骤。但是,我的arrayadapter没有更新。任何建议 – 2013-07-25 13:55:33

+2

请举一些例子。 – 2013-11-06 21:40:21