http://april19880317.blog.51cto.com/1938095/690380
ListView是Android中经常会使用的东西,绑定数据对于初学者来说,尤其是刚接触编程的人来说,往往会觉得很难理解,我上大二的时候学的java,但是基本上相当于没有学,什么都没写过,真正接触编程就是开始上手学android,把这些记录下来,自己可以回头看下,也可以让新手更好的理解。高手绕过....
Android中Adapter我是这么理解的,是数据和视图之间的桥梁,数据在adapter中做处理,然后显示到视图上面。
Adapter有很多种,有ArrayAdapter<T>,BaseAdapter, CursorAdapter, HeaderViewListAdapter, ListAdapter, ResourceCursorAdapter, SimpleAdapter, SimpleCursorAdapter, SpinnerAdapter, WrapperListAdapter.
我在项目中用到过的就ArrayAdapter<T>, (数组也可以是对象数组),BaseAdapter(所有Adapter的基类),SimpleAdapter,CursorAdapter(数据来源是cursor),SimpleCursorAdapter,感觉有必要总结一下。
最基本的要数sdk官网上面给的这个代码例子了http://developer.android.com/resources/tutorials/views/hello-listview.html。
我自己写的一个例子,先上图,再贴上代码:
- package com.cz.list.demo;
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.ArrayAdapter;
- import android.widget.ListView;
- public class ArrayListDemo extends Activity {
- private ListView listView;
- private String[] adapterData;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.array_list_layout);
- /* 找到这个listView */
- listView = (ListView) findViewById(R.id.array_list);
- /* 我们要在listView上面没条显示的数据,放到一个数组中 */
- adapterData = new String[] { "Afghanistan", "Albania", "Algeria",
- "American Samoa", "Andorra", "Angola", "Anguilla",
- "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia",
- "Aruba", "Australia", "Austria", "Azerbaijan", "Bahrain",
- "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize",
- "Benin", "Bermuda", "Bhutan", "Bolivia",
- "Bosnia and Herzegovina", "Botswana", "Bouvet Island" };
- /* 这个是数组string类型的数组 */
- // ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
- // ArrayListDemo.this, android.R.layout.simple_list_item_1,
- // adapterData);
- /* 设置ListView的Adapter */
- listView.setAdapter(new ArrayAdapter<String>(ArrayListDemo.this,
- android.R.layout.simple_list_item_1, adapterData));
- }