ListView详解3

来源:互联网 发布:淘宝提醒买家付款 编辑:程序博客网 时间:2024/05/01 16:51

三、SimpleAdapter

SimpleAdapter可以自定义拓展listview。

使用simpleAdapter的数据用一般都是HashMap构成的List,list的每一节对应ListView的每一行。HashMap的每个键值数据映射到布局文件中对应id的组件上。因为系统没有对应的布局文件可用,我们可以自己定义一个布局vlist.xml。下面做适配,new一个SimpleAdapter参数一次是:this,布局文件,HashMap的 title 和 info,img。布局文件的组件id,title,info,img。布局文件的各组件分别映射到HashMap的各元素上,完成适配。

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="horizontal" android:layout_width="fill_parent"    android:layout_height="fill_parent">    <ImageView android:id="@+id/img"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_margin="5px"/>     <LinearLayout android:orientation="vertical"        android:layout_width="wrap_content"        android:layout_height="wrap_content">         <TextView android:id="@+id/title"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="22px" />        <TextView android:id="@+id/info"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="13px" />    </LinearLayout></LinearLayout>
布局文件

public class MainActivity extends ListActivity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);SimpleAdapter adapter = new SimpleAdapter(this, getData(),R.layout.activity_main,new String[] { "title", "info", "img" }, new int[] {R.id.title, R.id.info, R.id.img });setListAdapter(adapter);}private List<Map<String, Object>> getData() {List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();Map<String, Object> map = new HashMap<String, Object>();map.put("title", "1");map.put("info", " 1 ");map.put("img", R.drawable.ic_launcher);list.add(map);map = new HashMap<String, Object>();map.put("title", "2");map.put("info", " 2 ");map.put("img", R.drawable.ic_launcher);list.add(map);map = new HashMap<String, Object>();map.put("title", "3");map.put("info", " 3 ");map.put("img", R.drawable.ic_launcher);list.add(map);return list;}}
显示效果如图



*使用simpleadapter我们可以显示许多自定义的复杂视图,但是按钮是无法在simpleadapter中使用的。


原创粉丝点击