Android开发-适配器优化

在android开发中,常用ListView、GridView来显示多项数据。对适配器加以优化能够让每次适配数据变得更加简单,性能更加高效。下面是适配器优化后的代码:

public abstract class CommonAdapter<T> extends BaseAdapter{
Context context;
int resId;
List<T> datas;
LayoutInflater layoutInflater;

public CommonAdapter(List<T> datas,Context context,int resId)
{
this.datas=datas;
this.context=context;
this.resId=resId;
layoutInflater=LayoutInflater.from(context);
}

@Override
public int getCount() {
return datas.size();
}

@Override
public Object getItem(int i) {
return datas.get(i);
}

@Override
public long getItemId(int i) {
return i;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {

T data = datas.get(i);


if(view==null)
{
view = layoutInflater.inflate(resId,null);

ViewHolder holder = new ViewHolder(view);
view.setTag(holder);

}

ViewHolder holder = (ViewHolder) view.getTag();
setData(data,holder,context);

return view;
}


public abstract void setData(T data, ViewHolder holder,Context context);

}
//创建一个类来保存控件
 
public class ViewHolder {

Map allview = new HashMap<>();
View item;
public ViewHolder(View item) {

this.item=item;
}

public View getView(int redid)
{

View v = allview.get(redid);
if(v==null)
{

View view = item.findViewById(redid);
allview.put(redid,view);
return view;
}
else{
return v;
}
}
}
//使用适配器:
public class ArticleAdapter extends CommonAdapter{
public ArticleAdapter(List datas, Context context, int resId) {
super(datas, context, resId);
}

@Override
public void setData(Article data, ViewHolder holder,Context context) {
ImageView logo = (ImageView)holder.getView(R.id.alogo);
TextView title = (TextView)holder.getView(R.id.aname);
logo.setImageBitmap(data.logo);
title.setText(data.title);
}
}
使用适配器时,传入数据,上下文,模板id即可

你可能感兴趣的:(Android开发-适配器优化)