AdapterView: ListView GridView Gallery Spinner
Adapter: SimpleAdapter SimpleCursorAdapter ArrayAdapter
[功能]
* AdapterView: 由界面決定用哪一種
* Adapter : 由數據形式決定用哪一種
AdapterView 沒什麼可說的 界面是人各有志 看自己的需要吧 所以今天主要介紹一下 Adapter 的使用
[前提]
因為與界面無關 所以為方便 界面統一使用 ListView 且:
Java代碼
- ListView lv = (ListView) findViewById(R.id.list);
Java代碼
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <ListView
- android:id="@+id/list"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- </LinearLayout>
* 使用所有Adapter
Java代碼
- lv.setAdapter(adapter);
以下逐一舉例:
[SimpleAdapter ]
* source code:
Java代碼
- public SimpleAdapter(Context context, List<? extends Map<String, ?>> data,
- int resource, String[] from, int[] to)
* sample
Java代碼
- public final static String COLUMN_1 = "name";
- public final static String COLUMN_2 = "phone";
-
- List<Map<String,String>> display;
-
- String[] from = {COLUMN_1,COLUMN_2};
- int[] to = {android.R.id.text1,android.R.id.text2};
- SimpleAdapter adapter = new SimpleAdapter(this, display,android.R.layout.simple_list_item_2, from,to);
* 補充:
1. 數據源 display
Java代碼
- 1. 定義: List<Map<String,String>> display;
-
-
- 2. 初始化: display = new ArrayList<Map<String,String>>();
-
-
- 3. 使用: display = addValue();
-
- public List<Map<String,String>> addValue(){
- List<Map<String,String>> value = new ArrayList<Map<String,String>>();
-
- Map<String,String> item1 = new HashMap<String,String>();
- item1.put(COLUMN_1, "griffin");
- item1.put(COLUMN_2, "132123");
- value.add(item1);
-
- Map<String,String> item2 = new HashMap<String,String>();
- item2.put(COLUMN_1, "eoe.android");
- item2.put(COLUMN_2, "132");
- value.add(item2);
-
- Map<String,String> item3 = new HashMap<String,String>();
- item3.put(COLUMN_1, "gryphone");
- item3.put(COLUMN_2, "132342");
- value.add(item3);
-
- return value;
- }
[SimpleCursorAdapter]
* source code
Java代碼
- public SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to)
* sample
Java代碼
- Cursor c = getContentResolver().query(People.CONTENT_URI,
- null, null, null, null);
-
- String[] from ={People.NAME};
- int[] to = {android.R.id.text1};
- SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
- android.R.layout.simple_list_item_1,c, from,to);
[ArrayAdapter]
* source code
Java代碼
- public ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)
* sample
Java代碼
- String[] value = {
- "JAN","FEB","MAR","APR",
- "MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC "
- };
-
- ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,value)