Android 之 ListView使用SimpleAdapter展示列表
2013-04-16 22:49 waddell 阅读(356) 评论(0) 编辑 收藏 举报SimpleAdapter是用的比较多的一种adapter,它的拓展性很好,可以自己定义布局,也可以设置一些图片等。
对于SimpleAdapter一般都需要自定义一个xml文件,是一个列表行的布局文件。
simpleitem.xml
<?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="horizontal" > <TextView android:id="@+id/id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:layout_weight="2" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="left" android:layout_weight="10"/> <TextView android:id="@+id/age" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_weight="3"/> </LinearLayout>
SimpleAdapterDemo.java
package com.example.phonedemo; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.example.phonedemo.util.Utils; import android.app.Activity; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SimpleAdapter; public class SimpleAdapterDemo extends Activity { private ListView listView = null; private LinearLayout layout = null; private List<Map<String, Object>> list = null; private SimpleAdapter adapter = null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); this.layout = new LinearLayout(this); this.layout.setOrientation(LinearLayout.VERTICAL); this.listView = new ListView(this); list = initList(); adapter = new SimpleAdapter(this, list, R.layout.simpleitem, new String[] { "id", "name", "age" }, new int[] { R.id.id, R.id.name, R.id.age }); this.listView.setAdapter(adapter); this.layout.addView(this.listView, Utils.match); super.addContentView(this.layout, Utils.match); } private List<Map<String, Object>> initList() { List<Map<String, Object>> temp = new ArrayList<Map<String, Object>>(); Map<String, Object> map = null; for (int i = 0; i < 20; i++) { map = new HashMap<String, Object>(); map.put("id", i); map.put("name", "张三" + i + "号"); map.put("age", 28); map.put("email", "zhangsan@163.com"); temp.add(map); } return temp; } }