情境
SimpleAdapter其實跟如何用baseAdapter自訂ListView差不多,
但是比BaseAdapter簡單許多,
前面有用GridView來示範,
因此現在來示範如何使用SimpleAdapter作一個自訂的ListView。
程式碼說明
先在xml宣告一個listview,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/list_view" />
</RelativeLayout>
然後初始化一些資料
private ListView listView;
private SimpleAdapter simpleAdapter;
private int[] image = {
R.drawable.cat, R.drawable.flower, R.drawable.hippo,
R.drawable.monkey, R.drawable.mushroom, R.drawable.panda,
R.drawable.rabbit, R.drawable.raccoon
};
private String[] imgText = {
"cat", "flower", "hippo", "monkey", "mushroom", "panda", "rabbit", "raccoon"
};
在onCreate呼叫SimpleAdapter
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView)findViewById(R.id.list_view);
List<Map<String, Object>> items = new ArrayList<Map<String,Object>>();
for (int i = 0; i < image.length; i++) {
Map<String, Object> item = new HashMap<String, Object>();
item.put("image", image[i]);
item.put("text", imgText[i]);
items.add(item);
}
simpleAdapter = new SimpleAdapter(this,
items, R.layout.item_layout, new String[]{"image", "text"},
new int[]{R.id.image, R.id.text});
listView.setAdapter(simpleAdapter);
}
然後建立一個xml給SimpleAdapter裝
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_height="50dp"
android:layout_width="50dp"
android:layout_gravity="center"
android:id="@+id/image" />
<TextView
android:layout_height="wrap_content"
android:id="@+id/text"
android:textSize="20sp"
android:gravity="center"
android:layout_width="match_parent"/>
</LinearLayout>
這邊就需要微調一下元件,
基本上跟GridView的寫法是相同的,非常的簡單。