2010-07-22 43 views
8

是否可以更新SimpleAdapter?我有一個數據列表和一個頁腳,上面寫着「查看下一個結果」當單擊該列表項時,我捕獲該事件並獲取新數據。然後我想用這個新數據替換ListView中的數據,但我無法弄清楚如何去做。有任何想法嗎?我不想使用ArrayAdapter,因爲據我所見,項目只能容納一個字符串,我需要它來容納多個字符串和整數。如何在Android中更新SimpleAdapter

回答

10

更新:根據del116,你確實可以給SimpleAdapter一個可變的地圖,然後手動調用適配器的notifyDataSetChanged方法,當你需要的名單進行更新。但是,我的觀點是關於SimpleAdapter的文檔,指定它是用於靜態數據;將其用於可變數據與其設計相反,所以如果您使用這種技術,我將確保在出現新的Android版本時繼續使用它。

(原文評論如下:)

如果你看看SimpleAdapter description它說,這是「一個簡單的適配器映射靜態數據在一個XML文件中定義的看法。」我已經添加了重點 - 簡單地說,SimpleAdapater不是爲了與更改的數據一起使用而構建的;它只處理靜態數據。如果因爲您的數據不止一位文本而無法使用ArrayAdapter,那麼您將必須構建自己的自定義ListAdapter,或將數據放入數據庫並使用其中一個CursorAdapter s。

作爲最後的手段,如果你並不需要太多的表現,你可以通過建立一個全新的SimpleAdapter實例的任何時候你的數據的變化,並告訴通過使用它的列表視圖更新由SimpleAdapter支持的ListViewsetListAdapter

+4

這裏的答案真的很具誤導性。更新數組數據並在我的SimpleAdapter上調用notifyDataSetChanged()之後,我能夠更新simpleAdapter。不需要使用ArrayAdapter來調用notifyDataSetChanged()。 – dell116 2011-03-16 19:19:54

+1

@ dell116夠公平的。我在回答結束時提到了這種可能性,但根據您的反饋,我已將其提升到最高水平,事實上它確實有效;我沒有測試過它。我仍然認爲做這樣的事情值得注意,因爲SimpleAdapter文檔明確指出它是用於靜態數據的。 – 2011-03-19 09:19:38

+0

現在回頭看...哇。我對編程或SimpleAdapter的預期目的一無所知。如果您使用的ListView(或任何AdapterView)支持的數據結構將更改不使用SimpleAdapter。 Foot.inMouth(真); – dell116 2018-01-17 23:28:24

2

SimpleAdapter是用於靜態數據,因此您的性能可能會有所不同。最好的解決方案可能是切換到不同類型的適配器,例如ArrayAdapter,或者每次更改數據集時都創建一個新的SimpleAdapter

3
ListView lv= (ListView) findViewById(R.id.loglist); 
ArrayList<Map<String, String>> list = buildData(); 
String[] from = { "time", "message" }; 
int[] to = { R.id.logtime, R.id.logmessage }; 

adapter = new SimpleAdapter(getApplicationContext(), list,R.layout.log_list_row, from,to); 
lv.setAdapter(adapter); 

每次調用此函數來更新ListView。請記住,你必須用新數據更新的列表變量..

希望這有助於.. :)

0

我是不是能夠得到notifyDataSetChanged()上更新我的SimpleAdapter工作,所以相反,我第一次嘗試去除附着於使用removeAllViews(),然後加入ListView的父佈局,所有的意見,而工作,讓我更新UI:

LinearLayout results = (LinearLayout)findViewById(R.id.results); 
ListView lv = new ListView(this); 
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>(); 
SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.directory_row, 
        new String[] { "name", "dept" }, new int[] { R.id.name, R.id.dept }); 

for (...) { 
    HashMap<String, String> map = new HashMap<String, String>(); 
    map.put("name", name); 
    map.put("dept", dept); 
    list.add(map); 
} 

lv.setAdapter(adapter); 
results.removeAllViews();  
results.addView(lv); 
-2
mySimpleAdapter.notifyDataSetChanged(); 

使用該行更新後數據中的數據HashMap地圖列表

+0

請閱讀文檔,如上所述SimpleAdapter上不可行SimpleAdapter不適用於此類操作。 – Manny265 2016-07-05 19:09:44