SimpleAdapter是擴(kuò)展性最好的適配器共屈,可以定義各種你想要的布局炫狱,而且使用很方便
SimpleAdapter(Contextcontext, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
- 參數(shù)context:上下文,比如this。關(guān)聯(lián)SimpleAdapter運(yùn)行的視圖上下文
- 參數(shù)data:Map列表,列表要顯示的數(shù)據(jù),這部分需要自己實(shí)現(xiàn)恢氯,如例子中的getData(),類型要與上面的一致鼓寺,每條項(xiàng)目要與from中指定條目一致
- 參數(shù)resource:ListView單項(xiàng)布局文件的Id,這個布局就是你自定義的布局了勋拟,你想顯示什么樣子的布局都在這個布局中。這個布局中必須包括了to中定義的控件id
- 參數(shù) from:一個被添加到Map上關(guān)聯(lián)每一個項(xiàng)目列名稱的列表妈候,數(shù)組里面是列名稱
- 參數(shù) to:是一個int數(shù)組敢靡,數(shù)組里面的id是自定義布局中各個控件的id,需要與上面的from對應(yīng)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//[1]找到控件
ListView lv = (ListView) findViewById(R.id.lv);
//[1.1]準(zhǔn)備listview 要顯示的數(shù)據(jù)
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", "關(guān)羽");
map4.put("phone", "119");
//[1.1]把map加入到集合中
data.add(map1);
data.add(map2);
data.add(map3);
data.add(map4);
//[2]設(shè)置數(shù)據(jù)適配器 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]設(shè)置數(shù)據(jù)適配器
lv.setAdapter(adapter);
}
}