您的位置:首页 > 移动开发 > Android开发

Android开发指南-用户界面-绑定数据

2010-06-21 22:59 513 查看
目录

用AdapterView绑定数据Binding to Data with AdapterView

用数据填充布局Filling the Layout with Data

处理用户的选择Handling User Selections

编辑本段 回目录用AdapterView绑定数据Binding to Data with AdapterView

AdapterView是ViewGroup的子类,其子视图由绑定某类型数据的适配器Adapter决定。AdapterView用于当你需要在布局中显示存储数据时(不是字符串或可绘制资源)。

画廊Gallery,列表视图ListView,和微调控件Spinner就是适配器视图AdapterView子类的例子,用来绑定到特定类型的数据并以一定的方式显示。

AdapterView对象有两个主要责任:

·用数据填充布局

·处理用户的选择

编辑本段 回目录用数据填充布局Filling the Layout with Data

通常是通过绑定AdapterView类到一个适配器Adapter来插入数据到布局中,这从外部获取数据(可能是代码中所提供的一个列表数据,或者是设备数据库中的查询结果)。

下面的代码示例执行以下操作:

1. 用现有的一个视图创建一个微调控件Spinner并将其绑定到一个新的ArrayAdapter,该适配器从本地资源中读取颜色数组。

2. 从一个视图创建另外的微调对象,并将其绑定到一个新的SimpleCursorAdapter,将从设备联系人中读取人名(见Contacts.People)。

复制到剪贴板 XML/HTML代码

// 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 adatper 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);

注意Projection中的People._ID列是必须的,否则你将收到一个异常。

如果,在你的应用程序生命周期过程中,你改变了适配器所读取的下层数据,你应该调用notifyDataSetChanged()方法。这将通知附着视图数据已经更改,它需要刷新自己。

编辑本段 回目录处理用户的选择Handling User Selections

你通过设置类的AdapterView.OnItemClickListener成员变量为一个侦听器来处理用户的选择并且捕获选择变化。

复制到剪贴板 Java代码

// 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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: