一、File:MainActivity.java
package com.jiangge.simpleadapterdemo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.list_view);
List<Map<String, Object>> data = new ArrayList<Map<String,Object>>();
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("nametext","这是第一个功能--帮助");
map1.put("iconid",R.drawable.help);
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("nametext","这是第二个功能--查找");
map2.put("iconid",R.drawable.search);
Map<String, Object> map3 = new HashMap<String, Object>();
map3.put("nametext","这是第三个功能--帮助");
map3.put("iconid",R.drawable.collections);
data.add(map1);
data.add(map2);
data.add(map3);
//Context context, List<? extends Map<String, ?>> data,int resource, String[] from, int[] to)
listView.setAdapter(new SimpleAdapter(this, data, R.layout.list_item, new String[]{"nametext","iconid"}, new int[]{R.id.text_view,R.id.image_view}));
}
}
参数意义:
data --> 绑定的数据,list集合
R.layout.list_item --> 数据显示对应的布局
要记数据和 view 对象建立一个映射关系
from [] --> map集合里的数据 key
to [] --> 布局文件里面的 id
二、布局文件:
res/layout/activity_main.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="vertical" >
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
res/layout/list_item.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" >
<ImageView
android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
三、效果图:
项目结构图片: