2012-02-21 138 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