SimpleAdapter是擴展性最好的適配器,可以定義各種你想要的布局,而且使用很方便
SimpleAdapter(Contextcontext, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
- 參數context:上下文,比如this。關聯SimpleAdapter運行的視圖上下文
- 參數data:Map列表,列表要顯示的數據,這部分需要自己實現,如例子中的getData(),類型要與上面的一致,每條項目要與from中指定條目一致
- 參數resource:ListView單項布局文件的Id,這個布局就是你自定義的布局了,你想顯示什么樣子的布局都在這個布局中。這個布局中必須包括了to中定義的控件id
- 參數 from:一個被添加到Map上關聯每一個項目列名稱的列表,數組里面是列名稱
- 參數 to:是一個int數組,數組里面的id是自定義布局中各個控件的id,需要與上面的from對應
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//[1]找到控件
ListView lv = (ListView) findViewById(R.id.lv);
//[1.1]準備listview 要顯示的數據
List<Map<String, String>> data = new ArrayList<Map<String,String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("name", "張飛");
map1.put("phone", "1388888");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("name", "趙云");
map2.put("phone", "110");
Map<String, String> map3 = new HashMap<String, String>();
map3.put("name", "貂蟬");
map3.put("phone", "13882223");
Map<String, String> map4 = new HashMap<String, String>();
map4.put("name", "關羽");
map4.put("phone", "119");
//[1.1]把map加入到集合中
data.add(map1);
data.add(map2);
data.add(map3);
data.add(map4);
//[2]設置數據適配器 resource 我們定義的布局文件
// from map集合的鍵
SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(), data, R.layout.item,
new String[]{"name","phone"}, new int[]{R.id.tv_name,R.id.tv_phone});
//[3]設置數據適配器
lv.setAdapter(adapter);
}
}