Devel/ui/binding
From Android中文网
Android中文网(androidcn.net) 版权申明 : creativecommons licenses
[编辑] 数据绑定
这部分会提及UI上面的现实组织. 这些组成对象是经典AdapterView类的子类.例如包括图像,数层结构表现.这些对象有2个通用的任务:
- 数据层的填充
- 用户操作选择
As we mentioned, some view groups have UI. These objects typically subclass AdapterView. Examples include such as Gallery (an image selection widget) and ListView (a list of views). These objects have two jobs in common:
- Filling the layout with data
- Handling user selections
[编辑] 数据层填充
典型的类
This is typically done by binding the class to an Adapter that gets its data from somewhere — either a list that the code supplies, or query results from the device's database.
// Get a Spinner and bind it to an ArrayAdapter that
// references a String array.
private String[] fruit = {"apples", "oranges", "lemons"}
Spinner s1 = (Spinner)findViewById(R.id.fruitlist);
s1.setAdapter(new ArrayAdapter<String>(this, mStrings));
// Load a Spinner and bind it to a data query.
private String[] cols={android.provider.Contacts.PeopleColumns.NAME};
private Cursor cur = managedQuery(android.provider.Contacts.People.CONTENT_URL, cols, null, null);
s2.setAdapter(new CursorAdapter(cur, this));
[编辑] 用户操作选择
设置类的AdapterView.OnItemClickListener 方法监听和捕捉用户的操作事件. This is done by setting the class's AdapterView.OnItemClickListener member to a listener and catching the selection changes.
// 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.
showAlert("You've got an event", "Clicked me!", "ok", false);
}
};
// Now hook into our object and set its onItemClickListener member
// to our class handler object.
mHistoryView = (ListView)findViewById(R.id.accept_button);
mHistoryView.setOnItemClickListener(mMessageClickedHandler);
