package com.example.utils; import android.content.Context; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ViewHolder { private SparseArray<View> mViews; private int mPosition; private View convertView; // 需要的参数 public ViewHolder(Context context, ViewGroup parent, int layoutId, int position) { /** * 进行初始化设置 */ mViews = new SparseArray<View>(); mPosition = position; convertView = LayoutInflater.from(context).inflate(layoutId, parent, false); convertView.setTag(this); } // viewHolder入口 public static ViewHolder get(Context context, View convertView, ViewGroup parent, int layoutId, int position) { // 如果为空则new出新的 if (convertView == null) { return new ViewHolder(context, parent, layoutId, position); } else { ViewHolder holder = (ViewHolder) convertView.getTag(); //更新position holder.mPosition = position; return holder; } } /** * 通过id获取控件 * @param id * @return */ public <T extends View> T getView(int id){ View view = mViews.get(id); if(view == null){ view = convertView.findViewById(id); mViews.put(id, view); } return (T) view; } public View getConvertView() { return convertView; } public int getPosition(){ return mPosition; } }
基类适配器
package com.example.utils; import java.util.List; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; public abstract class CommonAdapter<T> extends BaseAdapter { protected List<T> data; protected Context mContext; public CommonAdapter(List<T> data,Context mContext){ this.data = data; this.mContext = mContext; } @Override public int getCount() { // TODO Auto-generated method stub return data.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return data.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public abstract View getView(int position, View convertView, ViewGroup parent); }
package com.example.bluetooth; import java.util.List; import com.example.utils.CommonAdapter; import com.example.utils.ViewHolder; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class MyAdapter extends CommonAdapter<Bean>{ public MyAdapter(List<Bean> data, Context mContext) { super(data, mContext); } @Override public View getView(int position, View convertView, ViewGroup parent) { //初始化 ViewHolder holder = ViewHolder.get(mContext, convertView, parent, R.layout.item, position); //设置值 TextView name = holder.getView(R.id.item_name); TextView address = holder.getView(R.id.item_address); name.setText(data.get(position).getName()); address.setText(data.get(position).getAddress()); //返回注意getConvertView return holder.getConvertView(); } }