構建自己的適配器類:
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>
什麼爲R .layout.my_list_item?我只有一個列表視圖。 –
我也不確定如何用我的物品填充視圖。 –
您可以創建自己的自定義佈局,以獲得行想要的樣子。這是R.layout.my_list_item。 –