Android ListView实现方法三(自定义适配器)

public abstract class ArrayListAdapter<T> extends BaseAdapter {

	protected List<T> mListData;
	protected Context mContext;
	
	public ArrayListAdapter(Context context){
		this.mContext = context;
	}
	
	
	public int getCount() {
		// TODO Auto-generated method stub
		if(mListData != null)
			return mListData.size();
		else
			return 0;
	}

	
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return mListData == null ? null : mListData.get(position);
	}

	
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	
	abstract public View getView(int position, View convertView, ViewGroup parent);
	
	/**
	 * setList
	 * @param list
	 */
	public void setListData(List<T> list){
		this.mListData = list;
		notifyDataSetChanged();
	}
	
	/**
	 * setList
	 * @param list
	 */
	public void setListData(T[] list){
		ArrayList<T> arrayList = new ArrayList<T>(list.length);  
		for (T t : list) {  
			arrayList.add(t);  
		}  
		setListData(arrayList);
	}
}

自定义adapter,通过继承以上adapter来定制各种适配器,如下所示:

public class SettingAdapter extends ArrayListAdapter<String> {

	/**
	 * @param context
	 */
	public SettingAdapter(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final ViewHolder holder;
		if (convertView == null) {
			convertView = LayoutInflater.from(mContext).inflate(
					R.layout.list_item, null);
			holder = new ViewHolder();
			holder.textView = (TextView)convertView.findViewById(R.id.text_name);
			holder.checkBox = (CheckBox) convertView.findViewById(R.id.cb_select);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		if (holder != null) {
			holder.textView.setText(mListData.get(position));
		}
		return convertView;
	}

	public static class ViewHolder {
		TextView textView;
		CheckBox checkBox;
	}
}
在该adapter中,加载listview行布局文件,并设置listview行中各控件的事件监听,listview数据绑定过程和 Android ListView实现方法二中类似。

你可能感兴趣的:(Android ListView实现方法三(自定义适配器))