android BaseAdapter 自定义适配器 BaseAdapter基类抽取 一
适配器基类
package com.zcycjy.mobile.adapter; import java.util.List; import android.content.Context; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; public abstract class UAdapter extends BaseAdapter { private Context context; private List<?> list; public UAdapter(Context context, List<?> list) { this.context = context; this.list = list; } @Override public int getCount() { return list == null ? 0 : list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } /** * 布局资源 * @return */ protected abstract int setLayoutRes(); /** * 重写getView方法 * @param position * @param convertView * @param parent * @param holder * @return */ protected abstract View getView(int position, View convertView, ViewGroup parent, ViewHolder holder); /** * 每个控件的缓存 */ protected class ViewHolder { public SparseArray<View> view = new SparseArray<View>(); /** * 指定resId和类型即可获取到相应的view * * @param convertView * @param resId * @param <T> * @return */ public <T extends View> T obtainView(View convertView, int resId) { View v = view.get(resId); if (null == v) { v = convertView.findViewById(resId); view.put(resId, v); } return (T) v; } } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (null == convertView) { holder = new ViewHolder(); convertView = LayoutInflater.from(context).inflate(setLayoutRes(), null); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } return getView(position, convertView, parent, holder); } }
继承积累UAdapter
package com.zcycjy.mobile.adapter; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.zcycjy.mobile.R; import com.zcycjy.mobile.entity.Address; public class AddressAdapter extends UAdapter { List<Address> list = null;// Address 实体累 public AddressAdapter(Context context, List<Address> list) { super(context, list); } public void refreshDatas(List<Address> list) { if (null != list) { this.list = list; notifyDataSetChanged(); } else { this.list = new ArrayList<Address>(); } } @Override protected int setLayoutRes() { return R.layout.item_address; } @Override protected View getView(int position, View convertView, ViewGroup parent, ViewHolder holder) { TextView tv = holder.obtainView(convertView, R.id.item_tv_name); Address ad = (Address) getItem(position); tv.setText(ad.getName()); return convertView; } }调用相信大家都会用,是不是感觉方便简单了点