1.定義
數據適配器是AdapterView視圖(如ListView - 列表視圖控件、Gallery - 縮略圖浏覽器控件、GridView - 網格控件、Spinner - 下拉列表控件、AutoCompleteTextView - 自動提示文本框、ExpandableListView - 支持展開/收縮功能的列表控件等)與數據之間的橋梁,用來處理數據並將數據綁定到AdapterView上。
2.作用
數據適配器是連接數據源和視圖界面的橋梁。
3.分類
包括ArrayAdapter(數組適配器)以及SimpleAdapter(簡單適配器)。其中:
4.實現
5.案例
(1)具體用到的類:
(2)代碼實例:
ListView listView;
ArrayAdapter arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_violet);
listView = (ListView) findViewById(R.id.listView);
String[] data={"蘋果","香蕉","桃子","西瓜"};
arrayAdapter=new ArrayAdapter(this,R.layout.abc_simple_dropdown_hint,data);//上下文,當前ListView加載的每一個列表所對應的布局文件,數據源)
listView.setAdapter(arrayAdapter);
}
ListView listView;
SimpleAdapter simpleAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_violet);
listView = (ListView) findViewById(R.id.listView);
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
String[] persons = {"張老師", "陳老師", "李老師", "黃老師"};
String[] phoneNums = {"18706218201", "18706214521", "13908761231", "18512390812"};
for (int i = 0; i < persons.length; i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("username", persons[i]);
map.put("phoneNum", phoneNums[i]);
//插入圖片
map.put("photo",R.drawable.cc);
data.add(map);
}
//(context,data,resource,from,to)
simpleAdapter = new SimpleAdapter(this, data, R.layout.list_item, new String[]{"username","photo", "phoneNum"}, new int[]{R.id.username,R.id.photo, R.id.phoneNum});
listView.setAdapter(simpleAdapter);
}
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11