public SimpleAdapter (Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
参数:
context |
上下文,一般为this |
data |
一个字典类型的list。每一项对应list中的一行。字典包含所有行,而且包含from中指定的所有列。 |
resource |
定义列表项布局的布局资源的id。应含有to中的所有项。 |
from |
map中要映射到list中的列名(键名) |
to |
显示from中列的视图。全为TextView 。与from中的顺序一一对应。 |
resource是item的视图,为listview中的行定义显示的样式,至少包含了to中的对象。
from是data中map的键,映射到to中的对象上显示。
通过构建list,并设置每项为一个map来实现:
创建TestList类继承Activity
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, Object>> users = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < 10; i++) {
HashMap<String, Object> user = new HashMap<String, Object>();
user.put("img", R.drawable.user);
user.put("username", "姓名(" + i+")");
user.put("age", (20 + i) + "");
users.add(user);
}
SimpleAdapter saImageItems = new SimpleAdapter(
this,
users,// 数据来源
R.layout.user,//每一个user xml 相当ListView的一个组件
new String[] { "img", "username", "age" },// 分别对应view 的id
new int[] { R.id.img, R.id.name, R.id.age });
// 获取listview
((ListView) findViewById(R.id.users)).setAdapter(saImageItems);
下面是main.xml的内容:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:text="用户列表" android:gravity="center"
android:layout_height="wrap_content"
android:layout_width="fill_parent" android:background="#DAA520"
android:textColor="#000000">
</TextView>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="姓名"
android:gravity="center" android:layout_width="160px"
android:layout_height="wrap_content" android:textStyle="bold"
android:background="#7CFC00">
</TextView>
<TextView android:text="年龄"
android:layout_width="170px" android:gravity="center"
android:layout_height="wrap_content" android:textStyle="bold"
android:background="#F0E68C">
</TextView>
</LinearLayout>
<ListView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/users">
</ListView>
</LinearLayout>
之中listView前面的可以说是标题行,listview相当于用来显示数据的容器,里面每行是一个用户信息,而用户信息是样子呢?
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
>
<TableRow >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/img">
</ImageView>
<TextView
android:layout_height="wrap_content"
android:layout_width="150px"
android:id="@+id/name">
</TextView>
<TextView
android:layout_height="wrap_content"
android:layout_width="170px"
android:id="@+id/age">
</TextView>
</TableRow>
</TableLayout>
也就是说每行包含了一个img 和2个文字信息。
这个文件以参数的形式通过adapter在listview中显示。