package com.example.baseadapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class MyAdapater extends BaseAdapter {
private List<itemBean> mList;
private LayoutInflater mInflater;
public MyAdapater(Context context, List<itemBean> itemBeanList) {
mList = itemBeanList;
mInflater = LayoutInflater.from(context);
}
@Override
//返回适配器中数据集中数据的个数
public int getCount() {
return mList.size();
}
@Override
//获取数据集中与指定索引对应的数据项
public Object getItem(int position) {
return mList.get(position);
}
@Override
//获取指定行对应的ID
public long getItemId(int position) {
return position;
}
@Override
//获取每个Item的显示内容
public View getView(int position, View convertView, ViewGroup parent) {
//*****************逗比式*****************************↓
//没有任何的优化处理,每次都新建一个view,效率低下
/*View view = mInflater.inflate(R.layout.item_layout, null);//第一个参数,需要装载到item中的布局文件;第二个参数,一般填null
ImageView imageView = view.findViewById(R.id.iv_image);
TextView title = view.findViewById(R.id.tv_title);
TextView content=view.findViewById(R.id.tv_content);
itemBean bean=mList.get(position);
imageView.setImageResource(bean.ItemImageReId);
title.setText(bean.ItemTitle);
content.setText(bean.ItemContent);
return view;*/
//*****************逗比式*****************************↑
//*****************普通式*****************************↓
//大量的findViewById耗费时间
/*if(convertView==null){//为空,缓冲池里没有缓存,避免了重复创建
convertView=mInflater.inflate(R.layout.item_layout,null);
}
ImageView imageView = convertView.findViewById(R.id.iv_image);
TextView title = convertView.findViewById(R.id.tv_title);
TextView content=convertView.findViewById(R.id.tv_content);
itemBean bean=mList.get(position);
imageView.setImageResource(bean.ItemImageReId);
title.setText(bean.ItemTitle);
content.setText(bean.ItemContent);
return convertView;*/
//*****************普通式*****************************↑
//*****************文艺式*****************************↓
//不仅利用了缓存,并且通过ViewHolder类来减少了FindViewById在时间上的浪费
ViewHolder viewHolder;
if(convertView==null){//为空,缓冲池里没有缓存
viewHolder=new ViewHolder();
convertView=mInflater.inflate(R.layout.item_layout,null);
viewHolder.imageView=convertView.findViewById(R.id.iv_image);
viewHolder.title=convertView.findViewById(R.id.tv_title);
viewHolder.content=convertView.findViewById(R.id.tv_content);
convertView.setTag(viewHolder);
//通过setTag将ViewHolder与ConvertView关联
}
else {
viewHolder = (ViewHolder) convertView.getTag();
itemBean bean=mList.get(position);
viewHolder.imageView.setImageResource(bean.ItemImageReId);
viewHolder.title.setText(bean.ItemTitle);
viewHolder.content.setText(bean.ItemContent);
}
return convertView;
//*****************文艺式*****************************↑
}
//创建内部类ViewHolder
class ViewHolder{
public ImageView imageView;
public TextView title;
public TextView content;
}
}