当我们的列表包含图片和文字信息时,ArrayAdapter就无法实现了,使用SimpleAdapter,activity中findViewById()获取到ListView对象,调用ListView对象的setAdapter()方法,参数中传入SimpleAdapter对象。每一条数据是一个Map集合,所有的数据是一个List集合
new SimpleAdapter(context,data,resource,from,to)
context上下文,data数据集合List<Map<String,Object>> ,resuorce布局资源,from是String[]是数据中Map集合的key,to是int[]是布局文件中key对应的控件的资源id
Data数据,先new出来ArrayList 再new出来HashMap,调用HashMap对象的put()方法放入键值对,图标的放入资源id R.drawable.xxxx,调用ArrayList对象的add()方法加入Map对象
SimpleAdapter的源代码,构造函数,把data,resource,from,to对象赋值给成员变量,通过Context对象的getSystemService(Context.LAYOUT_INFLATER_SERVICE)方法获取LayoutInflater布局填充器对象赋值给成员变量。同样有getCount()方法和getView()方法,getView()中进行处理取出单条Map对象,根据to这个资源id的int[] 获取控件然后进行绑定。
activity代码:
代码语言:javascript复制package com.tsh.myadapter;
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.ArrayAdapter;
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 lv_list=(ListView) findViewById(R.id.lv_list);
List<Map<String, Object>> data=new ArrayList<Map<String,Object>>();
Map<String,Object> map1=new HashMap<String,Object>();
map1.put("tv_name","电话");
map1.put("iv_icon", R.drawable.ic_menu_call);
Map<String,Object> map2=new HashMap<String,Object>();
map2.put("tv_name","短信");
map2.put("iv_icon", R.drawable.ic_menu_btn_add);
Map<String,Object> map3=new HashMap<String,Object>();
map3.put("tv_name","摄像");
map3.put("iv_icon", R.drawable.ic_menu_camera);
data.add(map1);
data.add(map2);
data.add(map3);
lv_list.setAdapter(new SimpleAdapter(this, data, R.layout.list2_item, new String[]{"tv_name","iv_icon"}, new int[]{R.id.tv_name,R.id.iv_icon}));
}
}