Binding to Data with AdapterView
AdapterView是ViewGroup的子類,它的子View是通過Adapter綁定的數據形式所決定的。AdapterView不管你想在何時顯示數據都是可用的。
Gallery、ListView和Spinner是AdapterView的子類的例子,你可以綁定特定數據並顯示。
AdapterView物件有兩個主要屬性:
- 把數據填充到佈局上。
- 處理用戶的選擇。
Filling the layout with data
插入到佈局的數據通常通過AdapterView綁定倒是配器上的,它從外部資源取得數據。
以下為例子:
- 建立Spinner,綁定一個新的ArrayAdapter,ArrayAdapter從資源中讀取顏色陣列。
- 從一個View建立另一個Spinner,並與SimpleCursorAdapter綁定,從聯絡人中讀取姓名。
// 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);
Handling User Selection
// 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,"You've 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);
沒有留言:
張貼留言