2014-10-09 44 views
0

目前,我使用HashMap<String, String>SimpleAdapter對象在我ListView顯示的用戶數據,但現在我想用含有真正的用戶對象的ArrayList<User>();更換HashMap<String, String>在android開發替換SimpleAdapter提高代碼質量

這裏是我的代碼:

HashMap<String, String> map = new HashMap<String, String>(); 

       map.put(TAG_USERNAME, c.getString(TAG_USERNAME)); 
       map.put(TAG_FIRSTNAME, c.getString(TAG_FIRSTNAME)); 
       map.put(TAG_LASTNAME, c.getString(TAG_LASTNAME)); 
       map.put(TAG_ADDRESS, c.getString(TAG_ADDRESS)); 
       usersList.add(map); 

[...]

ListAdapter adapter = new SimpleAdapter(this, usersList, 
        R.layout.single_user, new String[] { TAG_USERNAME, 
          TAG_FIRSTNAME, TAG_LASTNAME, TAG_ADDRESS }, 
        new int[] { R.id.textViewUsername, R.id.textViewFirstName, 
          R.id.textViewLastName, R.id.textViewAddress }); 

這怎麼可能取代HashMapArrayList?有沒有爲此目的的特定班級?

任何幫助將不勝感激。

回答

0

最簡單的方法是在用戶類中覆蓋toString以便返回想要顯示的信息並使用ArrayAdapter<User>。或者你可以有你的CustomAdapter,它擴展了BaseAdapter並且實現了它的抽象方法。特別是您有getCount方法,該方法返回數據集保存的元素數量,getItem(int position)(返回數據集位置的對象)和getView(int, View, ViewGroup),您必須使用該方法來充氣和自定義視圖

+0

謝謝你的幫助。當使用'ArrayAdapter '時,我需要遍歷我的'ArrayList '並始終調用'user.toString()'以獲取所有用戶信息的Array,對吧? – user3475602 2014-10-09 18:07:39

+0

不,適配器會照顧它 – Blackbelt 2014-10-09 18:09:06

+0

好吧,但是當我像這樣調用它'ListAdapter arrAdapter = new ArrayAdapter (this,R.layout.single_user,usersArrList);''我得到''java.lang.IllegalStateException:ArrayAdapter需要資源ID爲TextView',因爲我有多個TextView,並且我無法將多個ID作爲參數應用,如'SimpleAdapter'。 – user3475602 2014-10-09 18:15:19