> AdapterView是ViewGroup的一個(gè)子類,由一個(gè)適配器,和綁定到適配器的某些類型的數(shù)據(jù)組合而成。當(dāng)你需要顯示一些存儲(chǔ)的數(shù)據(jù)時(shí),AdapterView是非常有用的。 Gallery、ListView和Spinner便是AdapterView的例子,他們可以讓你使用一些特殊格式的數(shù)據(jù)并且用一種特定的方式來顯示這些數(shù)據(jù)。 ApapterView對(duì)象有兩個(gè)主要職責(zé): @ 用數(shù)據(jù)來填充視圖 @ 處理用戶的操作事件 把數(shù)據(jù)插入到視圖里,通常是由綁定適配器的AdapterView類來完成的,通常是從一些額外的存儲(chǔ)中獲得的數(shù)據(jù),比如代碼來提供或者從設(shè)備的數(shù)據(jù)庫中查詢的結(jié)果集。例如下面的代碼: 1-使用一個(gè)已存在的View建立一個(gè)Spinner,然后綁定一個(gè)ArrayAdapter類來從本地資源里讀取顏色列表。 2-建立另一個(gè)Spinner對(duì)象,綁定到一個(gè)SimpleCursorAdapter類,然后從手機(jī)的聯(lián)系人列表讀取聯(lián)系人的名字。
- // Get a Spinner and bind it to an ArrayAdapter that
// references a String array.
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, R.array.colors, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
// Load a Spinner and bind it to a data query.
private static String[] PROJECTION = new String[] {
People._ID, People.NAME
};
Spinner s2 = (Spinner) findViewById(R.id.spinner2);
Cursor cur = managedQuery(People.CONTENT_URI, PROJECTION, null, null);
SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, // Use a template
// that displays a
// text view
cur, // Give the cursor to the list adapter
new String[] {People.NAME}, // Map the NAME column in the
// people database to...
new int[] {android.R.id.text1}); // The "text1" view defined in
// the XML template
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s2.setAdapter(adapter2);
復(fù)制代碼注意:在PROJECTION字段中,你必須有一個(gè)People._ID列,否則會(huì)拋出一個(gè)異常。如果期間你修改了數(shù)據(jù),那么需要調(diào)用一下notifyDataSetChanged()方法。這樣視圖便會(huì)做出相應(yīng)更新。 通過實(shí)現(xiàn)AdapterView.onItemClickListener監(jiān)聽器類,來獲取用戶的選擇。 - // Create a message handling object as an anonymous class.
private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id)
{
// Display a messagebox.
Toast.makeText(mContext,"Youve got an event",Toast.LENGTH_SHORT).show();
}
};
// Now hook into our object and set its onItemClickListener member
// to our class handler object.
mHistoryView = (ListView)findViewById(R.id.history);
mHistoryView.setOnItemClickListener(mMessageClickedHandler);
復(fù)制代碼
|