安卓ApiDemos学习 app/Activity/QuickContactsDemo

来源:互联网 发布:ant 执行指定java 编辑:程序博客网 时间:2024/05/17 08:41

这是一个ContentResolver应用的例子

首先构筑Cursor

        String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("                + Contacts.HAS_PHONE_NUMBER + "=1) AND ("                + Contacts.DISPLAY_NAME + " != '' ))";        Cursor c =                getContentResolver().query(Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select,                null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
检索条件用的SQLite语法

query方法中,第一个参数是数据提供者的URI:Contacts.CONTENT_URI --通信录

第二个参数是需要返回的列

第三个参数是检索条件

COLLATE LOCALIZED 表示用本地语言文字排序


紧接着,调用startManagingCursor(c);

将Cursor的生命周期与Activity同步。这样就可以不用显示关闭Cursor了


本例中,主画面是一个ListActivity,所以使用如下语句绑定

        ContactListItemAdapter adapter = new ContactListItemAdapter(this, R.layout.quick_contacts, c);        setListAdapter(adapter);

下面是核心,自定义的ResourceCursorAdapter

    private final class ContactListItemAdapter extends ResourceCursorAdapter {        public ContactListItemAdapter(Context context, int layout, Cursor c) {            super(context, layout, c);        }        @Override        public void bindView(View view, Context context, Cursor cursor) {            final ContactListItemCache cache = (ContactListItemCache) view.getTag();            TextView nameView = cache.nameView;            QuickContactBadge photoView = cache.photoView;            // Set the name            cursor.copyStringToBuffer(SUMMARY_NAME_COLUMN_INDEX, cache.nameBuffer);            int size = cache.nameBuffer.sizeCopied;            cache.nameView.setText(cache.nameBuffer.data, 0, size);            final long contactId = cursor.getLong(SUMMARY_ID_COLUMN_INDEX);            final String lookupKey = cursor.getString(SUMMARY_LOOKUP_KEY);            cache.photoView.assignContactUri(Contacts.getLookupUri(contactId, lookupKey));        }        @Override        public View newView(Context context, Cursor cursor, ViewGroup parent) {            View view = super.newView(context, cursor, parent);            ContactListItemCache cache = new ContactListItemCache();            cache.nameView = (TextView) view.findViewById(R.id.name);            cache.photoView = (QuickContactBadge) view.findViewById(R.id.badge);            view.setTag(cache);            return view;        }    }

newView方法中,生成Catch用存放通信录信息,nameView对应姓名,photoView对应图标
bindView方法中,将查询结果放入nameView和photoView中


效果如下







原创粉丝点击