SimpleCursorAdapter skd的解释是这样的:An easy adapter to map columns from a cursor to TextViews or ImageViews defined in an XML file. You can specify which columns you want, which views you want to display the columns, and the XML file that defines the appearance of these views。简单的说就是方便把从游标得到的数据进行列表显示,并可以把指定的列映射到对应的TextView中。 下面的程序是从电话簿中把联系人显示到类表中。先在通讯录中添加一个联系人作为数据库的数据。然后获得一个指向数据库的Cursor并且定义一个布局文件(当然也可以使用系统自带的)。 - /**
- * @author allin
- *
- */
- public class MyListView2 extends Activity {
-
- private ListView listView;
- //private List<String> data = new ArrayList<String>();
- @Override
- public void onCreate(Bundle savedInstanceState){
- super.onCreate(savedInstanceState);
-
- listView = new ListView(this);
-
- Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
- startManagingCursor(cursor);
-
- ListAdapter listAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_expandable_list_item_1,
- cursor,
- new String[]{People.NAME},
- new int[]{android.R.id.text1});
-
- listView.setAdapter(listAdapter);
- setContentView(listView);
- }
-
-
- }
复制代码Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);先获得一个指向系统通讯录数据库的Cursor对象获得数据来源。 startManagingCursor(cursor);我们将获得的Cursor对象交由Activity管理,这样Cursor的生命周期和Activity便能够自动同步,省去自己手动管理Cursor。 注意:需要在AndroidManifest.xml中如权限:<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
SimpleCursorAdapter 构造函数前面3个参数和ArrayAdapter是一样的,最后两个参数:一个包含数据库的列的String型数组,一个包含布局文件中对应组件id的int型数组。其作用是自动的将String型数组所表示的每一列数据映射到布局文件对应id的组件上。上面的代码,将NAME列的数据一次映射到布局文件的id为text1的组件上。 运行后效果如下图:
|