2013-10-28 27 views
1

我是Android編程的初學者,對於這個簡單的任務我有很大的麻煩。將Hashmap數組添加到列表視圖

我有一個ArrayList的:

ArrayList<HashMap<String, String>> tableList = new ArrayList<HashMap<String, String>>(); 

我想每個鍵/值對添加到ListView。

如何將它們添加到ListView?我已經看到無數在線使用適配器的解釋,但它們都使用我一無所知的變量。

回答

2

構建自己的適配器類:

public class MyAdapter extends BaseAdapter { 

    private Activity activity; 
    private HashMap<String, String> map; 

    public MyAdapter(Activity activity, HashMap<String, String> map) { 
     this.activity = activity; 
     this.map = map; 
    } 

    public int getCount() { 
     return map.size(); 
    }  

    public View getView(final int position, View convertView, ViewGroup parent) { 
     if (convertView == null) { 
      LayoutInflater inflater = (LayoutInflater) activity 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      convertView = inflater.inflate(R.layout.my_list_item, 
        null); 
     } 

      // Recommended to use a list as the dataset passed in the constructor. 
      // Otherwise not sure how you going to map a position to an index in the dataset. 
      String key = // get a key from the HashMap above 
      String value = map.get(key); 

      TextView keyView = convertView.findViewById(R.id.item_key); 
      keyView.setText(key); 

      TextView valueView = convertView.findViewById(R.id.item_value); 
      valueView .setText(value); 

     return convertView; 
    }  
} 

然後,把它傳遞到您的ListView setAdapter方法:

MyAdapter myAdapter = new MyAdapter(this, map); 
ListView listview = (ListView) findViewById(R.id.listview); 
listview.setAdapter(myAdapter); 

樣品佈局/ my_list_item.xml:

<LinearLayout xmlns:android:http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
> 

    <TextView 
     android:id="@+id/item_key" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
    /> 

    <TextView 
     android:id="@+id/item_value" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
    /> 
</LinearLayout> 
+0

什麼爲R .layout.my_list_item?我只有一個列表視圖。 –

+0

我也不確定如何用我的物品填充視圖。 –

+0

您可以創建自己的自定義佈局,以獲得行想要的樣子。這是R.layout.my_list_item。 –