Ifree团队 2013-07-08
原文自:http://android.eoe.cn/topic/ui
AdapterView是ViewGroup的一个子类,它决定view绑定什么类型的数据。AdapterView是非常有用的,只要你想把数据(不是资源文件夹里的Strings或者是drawables)显示在界面上你就会用到它。
Gallery,ListView,Spinner是AdapterVIew子类的实例,你可以给他们绑定特定类型的数据并以某一种方式显示这些数据。
AdapterView类有两方面的作用:
1 把数据填充到界面上
2 处理用户的选择
把数据显示在界面上通常的做法是把代码里获得的List的数据或者从数据库查询出来的结果集绑定到Adapter上。
比如:
1 创建一个Spinner,绑定数据到ArrayAdapter上
2 创建一个Spinner,绑定数据到SimpleCuisorAdapter上
代码:
// 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);
如果数据发生改变,你需要回调 notifyDataSetChanged(). 自动刷新View上的数据。
通过设置AdapterView.OnItemClickListener方法来处理用户的选择某一个位置的列表项
例如代码
// 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);