Using the default contact picker photo in my app
In my app I have a ListView of contacts with basic information (name, phone number) as well as the contact image, very similar to the default Android contact picker. If the contact has no image, it displays the app icon in its place. However, I would like to use the default silhouette image that the contact picker uses instead. My question is how can I access this image and use it in my app? Here is the section of my code that loads the contact image:
Contact c = new Contact();
final String[] projection = new String[] {
Contacts.DISPLAY_NAME, // the name of the contact
Contacts.PHOTO_ID // the ID of the column in the data table for the image
};
final Cursor contact = getContentResolver().query(
Contacts.CONTENT_URI,
projection,
Contacts._ID + "=?", // filter entries on the basis of the contact id
new String[] {String.valueOf(contactId)}, // the parameter which the contact id column is compared to
null
);
if(contact.moveToFirst()) {
final String name = contact.getString(
contact.getColumnIndex(Contacts.DISPLAY_NAME));
final String photoId = contact.getString(
contact.getColumnIndex(Contacts.PHOTO_ID));
// Get photo data for this contact
if(photoId != null) {
final Cursor photo = managedQuery(
Data.CONTENT_URI,
new String[] {Photo.PHOTO}, // column for the photo blob
Data._ID + "=?", // select row by id
new String[] {photoId}, // filter by photoId
null
);
// Convert photo blob 开发者_如何学Cto a bitmap
if(photo.moveToFirst()) {
byte[] photoBlob = photo.getBlob(
photo.getColumnIndex(Photo.PHOTO));
final Bitmap photoBitmap =
BitmapFactory.decodeByteArray(photoBlob, 0, photoBlob.length);
c.setPhoto(photoBitmap);
}
}
c.setName(name);
Here is the code in my ContactAdapter class which associates the ImageView with the contacts photo:
ImageView photo = (ImageView) v.findViewById(R.id.contact_photo);
if(photo != null) {
if(c.hasPhoto()) photo.setImageBitmap(c.getPhoto());
else photo.setImageResource(R.drawable.app_icon);
}
There are actually 3 different images that are used in Android. You can find them in the drawable folder of the resources that come with the emulator, or you can download them from here:
精彩评论