显示联系人头像和名字
package com.gaotong.buddy.adapter; import java.io.InputStream; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.provider.ContactsContract; import android.provider.ContactsContract.Contacts; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; import com.gaotong.buddy.R; public class ContactCursorAdapter extends CursorAdapter { private Context context; public ContactCursorAdapter(Context context, Cursor c, boolean autoRequery) { super(context, c, autoRequery); } public ContactCursorAdapter(Context context, Cursor c) { super(context, c); this.context = context; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { final LayoutInflater inflater = LayoutInflater.from(context); final View view = inflater.inflate(R.layout.contacts_list_item, null); final ContactItem contactItem = new ContactItem(); contactItem.imageView = (ImageView) view.findViewById(R.id.imgchoose); contactItem.textView = (TextView) view.findViewById(R.id.txtchoose); view.setTag(contactItem); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { final ContactItem contactItem = (ContactItem) view.getTag(); ImageView imgHead = contactItem.imageView; TextView txtName = contactItem.textView; long contactId = cursor.getLong(0); imgHead.setImageBitmap(getContactHead(contactId)); txtName.setText(getContactDisplayName(contactId)); } private String getContactDisplayName(long contactId) { String contactName = null; Cursor c = context.getContentResolver().query( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), new String[] { Contacts.DISPLAY_NAME }, null, null, null); try { if (c != null && c.moveToFirst()) { contactName = c.getString(0); } } finally { if (c != null) { c.close(); } } if (contactName == null) { contactName = ""; } return contactName; } private Bitmap getContactHead(long contactId) { Bitmap bitmap = null; // Cursor c = // context.getContentResolver().query(ContentUris.withAppendedId(Contacts.CONTENT_URI, // contactId), new String[] {Contacts.PHOTO_ID}, null, null, null); ContentResolver cr = context.getContentResolver(); Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); InputStream input = Contacts.openContactPhotoInputStream( context.getContentResolver(), uri); if (input != null) { bitmap = BitmapFactory.decodeStream(input); } else { bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.head0); } return bitmap; } } class ContactItem { ImageView imageView; TextView textView; }