Adapter :适配器
链接后端数据与前端显示适配接口,是数据(data)与UI(View)之间一个重要纽带,常见的View(ListView,GridView)等地方都会使用到Adapter,下图直观表达了Data、Adapter、View三者关系:
比较常用Adapter : BaseAdapter
使用BaseAdapter需要重写如下方法,
class MyAdapter extends BaseAdapter
{
private Context context;
public MyAdapter(Context context)
{
this.context = context;
}
@Override
public int getCount() {
// How many items are in the data set represented by this Adapter.(在此适配器中所代表的数据集中的条目数)
return 0;
}
@Override
public Object getItem(int position) {
// Get the data item associated with the specified position in the data set.(获取数据集中与指定索引对应的数据项)
return null;
}
@Override
public long getItemId(int position) {
// Get the row id associated with the specified position in the list.(取在列表中与指定索引对应的行id)
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get a View that displays the data at the specified position in the data set.
return null;
}
}
其中getView()方法很重要,涉及到内存优化与回收,需要引入缓冲contentView
(缓存contentView的方式可以判断如果缓存中不存在View才创建View,如果已经存在可以利用缓存中的View,提升了性能)与静态类ViewHolder
//在外面先定义,ViewHolder静态类
static class ViewHolder
{
public ImageView img;
public TextView title;
public TextView info;
}
//然后重写getView
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null)
{
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item, null);
holder.img = (ImageView)item.findViewById(R.id.img)
holder.title = (TextView)item.findViewById(R.id.title);
holder.info = (TextView)item.findViewById(R.id.info);
convertView.setTag(holder);
}else
{
holder = (ViewHolder)convertView.getTag();
}
holder.img.setImageResource(R.drawable.ic_launcher);
holder.title.setText("Hello");
holder.info.setText("World");
}
return convertView;
}