Android开发适配器系列:ListView使用自定义适配器(显示所有的联系人)

时间:2021-04-24 22:42:53
在开发中,我们经常使用到ListView这个控件。Android的AdivI也提供了许多创建ListView适配器的快捷方式。例如ArrayAdadivter、SimdivleAdadivter和SimdivleCursorAdadivter等。但你是否发现,如果采用这些系统自带的适配器,对于事件的响应只能局限在一个行单位。假设一行里面有一个按钮和一个图片控件,它们之间的响应操作是不一样的。若采用系统自带的适配器,就不能精确到每个控件的响应事件。这时,我们一般采取自定义适配器来实现这个比较精确地请求。
ListView的创建,一般要具备两大元素:
1)数据集,即要映射的字符串、图片信息之类。
2)适配器,实现把要映射的字符串、图片信息映射成视图(如Textview、Image等组件),再添加到ListView中。
一、实现细节:
下面是一个实操例子:
1、创建数据集,一般定义如下
private ArrayList<Contacts> contacts = new ArrayList<Contacts>();
2、创建适配器
public class MyListAdapter extends BaseAdapter {
	private ArrayList<Contacts> contacts = null;
	private Context mContext = null;
	public MyListAdapter(ArrayList<Contacts> contacts,Context mContext) {
		super();
		this.contacts = contacts;
		this.mContext = mContext;
	}
......
}
3、将适配器绑定到ListView控件
myAdapter = new MyListAdapter(contacts,this);
setListAdapter(myAdapter);
4、将R.layout.item布局作为一个视图,添加到listView中:
ListItemView listItemView = new ListItemView();
        if (convertView == null || position < contacts.size()) {  
	        convertView = LayoutInflater.from(mContext).inflate(R.layout.item, null);  
	        listItemView.iamge = (ImageView) convertView.findViewById(R.id.color_image);  
	        listItemView.title = (TextView) convertView.findViewById(R.id.color_title);  
	        listItemView.text = (TextView) convertView.findViewById(R.id.color_text);  
	        convertView.setTag(listItemView);
        }else{
        	listItemView = (ListItemView) convertView.getTag();
        }
二、实例源码:
AndroidManifest.xml
 <!-- 读取联系*限 -->
    <uses-permission android:name="android.permission.READ_CONTACTS" />
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </ListView>

</RelativeLayout>
item.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/color_image"
        android:layout_width="40dip"
        android:layout_height="40dip" />

    <TextView
        android:id="@+id/color_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/color_image"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:textSize="15dip"
        android:text="andy" />

    <TextView
        android:id="@+id/color_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/color_title"
        android:layout_toRightOf="@+id/color_image"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:textSize="20dip"
        android:text="1234567890" />

</RelativeLayout>
Contacts.java
package com.andieguo.listcontacts;

import android.graphics.Bitmap;

public class Contacts {
	private String name;
	private String number;
	private Bitmap photo;
	
	public Contacts(String name, String number, Bitmap photo) {
		super();
		this.name = name;
		this.number = number;
		this.photo = photo;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getNumber() {
		return number;
	}
	public void setNumber(String number) {
		this.number = number;
	}
	public Bitmap getPhoto() {
		return photo;
	}
	public void setPhoto(Bitmap photo) {
		this.photo = photo;
	}
}
MyListAdapter.java
package com.andieguo.listcontacts;

import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MyListAdapter extends BaseAdapter {
	private ArrayList<Contacts> contacts = null;
	private Context mContext = null;
	public MyListAdapter(ArrayList<Contacts> contacts,Context mContext) {
		super();
		this.contacts = contacts;
		this.mContext = mContext;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return contacts.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}
	public final class ListItemView {//提供缓存
		public ImageView iamge = null;  
		public TextView title = null;  
		public TextView text = null; 
	}
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ListItemView listItemView = new ListItemView();
        if (convertView == null || position < contacts.size()) {  
	        convertView = LayoutInflater.from(mContext).inflate(R.layout.item, null);  
	        listItemView.iamge = (ImageView) convertView.findViewById(R.id.color_image);  
	        listItemView.title = (TextView) convertView.findViewById(R.id.color_title);  
	        listItemView.text = (TextView) convertView.findViewById(R.id.color_text);  
	        convertView.setTag(listItemView);
        }else{
        	listItemView = (ListItemView) convertView.getTag();
        }
        //绘制联系人名称  
        listItemView.title.setText(contacts.get(position).getName());  
        //绘制联系人号码  
        listItemView.text.setText(contacts.get(position).getNumber());  
        //绘制联系人头像  
        listItemView.iamge.setImageBitmap(contacts.get(position).getPhoto());  
        return convertView;  
	}

}
MainActivity.java
package com.andieguo.listcontacts;

import java.io.InputStream;
import java.util.ArrayList;

import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;

import android.app.ListActivity;
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.text.TextUtils;
import android.view.Menu;
import android.widget.ListView;

public class MainActivity extends ListActivity {// 需要在main.xml文件中<ListView android:id="@android:id/list"></ListView>
	/** 获取库Phon表字段 **/
	private static final String[] PHONES_PROJECTION = new String[] {
			Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID, Phone.CONTACT_ID };
	/** 联系人显示名称 **/
	private static final int PHONES_DISPLAY_NAME_INDEX = 0;
	/** 电话号码 **/
	private static final int PHONES_NUMBER_INDEX = 1;
	/** 头像ID **/
	private static final int PHONES_PHOTO_ID_INDEX = 2;
	/** 联系人的ID **/
	private static final int PHONES_CONTACT_ID_INDEX = 3;
	private ArrayList<Contacts> contacts = new ArrayList<Contacts>();
	private ListView mListView = null;
	private MyListAdapter myAdapter = null;
	private Context mContext = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mContext = this;
		mListView = this.getListView();
		/** 得到手机通讯录联系人信息 **/
		getPhoneContacts();
		myAdapter = new MyListAdapter(contacts,this);
		setListAdapter(myAdapter);
	}

	private void getPhoneContacts() {
		// TODO Auto-generated method stub
		ContentResolver resolver = mContext.getContentResolver();  
	    // 获取手机联系人  
	    Cursor phoneCursor = resolver.query(Phone.CONTENT_URI,PHONES_PROJECTION, null, null, null);  
	    if (phoneCursor != null) {  
	        while (phoneCursor.moveToNext()) {  
		        //得到手机号码  
		        String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);  
		        //当手机号码为空的或者为空字段 跳过当前循环  
		        if (TextUtils.isEmpty(phoneNumber))  
		            continue;  
		        //得到联系人名称  
		        String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);  
		        //得到联系人ID  
		        Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);  
		        //得到联系人头像ID  
		        Long photoid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);  
		        //得到联系人头像Bitamp  
		        Bitmap contactPhoto = null;  
		        //photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的  
		        if(photoid > 0 ) {  
		            Uri uri =ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,contactid);  
		            InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);  
		            contactPhoto = BitmapFactory.decodeStream(input);  
		        }else {  
		            contactPhoto = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);  
		        }  
		        Contacts contact = new Contacts(contactName, phoneNumber, contactPhoto);
				contacts.add(contact);
	        }  
	        phoneCursor.close();
	    }
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
参考: