SimpleAdapter创建ListView

来源:互联网 发布:阿里云节点选择 编辑:程序博客网 时间:2024/05/22 00:42

SimpleAdapter必须接受List <? extends Map <String, ?>>数据,

ArrayList<HashMap<String, Object>> users = CreateListMapUserDate();


其中List每一个元素代表ListView一行,

Map中?代表每行中要显示的的元素,String代表这个元素的名称

产生用户数据private ArrayList<HashMap<String, Object>> CreateListMapUserDate() {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>();//给每行中每一个View赋值user.put("img", R.drawable.user);user.put("username", "姓名(" + i+")");user.put("age", (1000 * i) + "");users.add(user);}return users;}


这个名称必须与构造函数中第三个参数String[]中的名字相对应,

构造函数中第四个参数是String[]对应的id号

SimpleAdapter saImageItems = new SimpleAdapter(this,users,// 数据来源R.layout.user,//每一个user.xml 相当ListView的一行//ListView中每行包括的view组的件名称new String[] { "img", "username", "age" },// ListView中每行包括的view对应的idnew int[] { R.id.img, R.id.name, R.id.age });//


构造函数第二个参数是每一行对应的布局文件

user.xml<?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> 

第一个参数是上下文
Adapter绑定的对象是一个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><ListViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/users"></ListView></LinearLayout>



0 0
原创粉丝点击