package top.omooo.admin.mybaseadapter;
import android.content.Context;
import android.util.Log;
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;
/**
* Created by Omooo on 2017/8/9.
*/
public class MyAdapter extends BaseAdapter {
//数据源与数据适配器绑定
private List<ItemBean> mList;
//布局装载器对象
private LayoutInflater mLayoutInflater;
//记录总共消耗的时间
private long mSumTime;
/**
* 将XML转换为View
* @param context 使用当前得Adapter的界面对象
* @param list 数据源
*/
public MyAdapter(Context context,List<ItemBean> list) {
mList=list;
mLayoutInflater=LayoutInflater.from(context);
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int i) {
return mList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
/**
* 返回每一项的数据内容
* @param i
* @param convertView
* @param viewGroup
* @return
*/
@Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
//都比式
// View view = mLayoutInflater.inflate(R.layout.item, null);
// ImageView imageView = view.findViewById(R.id.imageView1);
// TextView title = view.findViewById(R.id.iv_title);
// TextView content = view.findViewById(R.id.iv_content);
// ItemBean bean = mList.get(i);
// Log.i("233", "getView: "+ mList.get(i));
// imageView.setImageResource(mList.get(i).ItemImageResid);
// title.setText(bean.ItemTitle);
// content.setText(bean.ItemContent);
// return view;
//普通式
// if (convertView == null) {
// convertView=mLayoutInflater.inflate(R.layout.item, null);
// }
// ImageView imageView = convertView.findViewById(R.id.imageView1);
// TextView title = convertView.findViewById(R.id.iv_title);
// TextView content = convertView.findViewById(R.id.iv_content);
// ItemBean bean = mList.get(i);
// imageView.setImageResource(mList.get(i).ItemImageResid);
// title.setText(bean.ItemTitle);
// content.setText(bean.ItemContent);
// return convertView;
//文艺式
/**
* 不仅利用了ListView的缓存,更通过ViewHolder类来实现显示数据的视图的缓存,避免多次findViewById寻找控件。
*/
//计时 获取系统的纳秒时间
long start = System.nanoTime();
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView=mLayoutInflater.inflate(R.layout.item, null);
viewHolder.imageView=convertView.findViewById(R.id.imageView1);
viewHolder.title=convertView.findViewById(R.id.iv_title);
viewHolder.content=convertView.findViewById(R.id.iv_content);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
ItemBean bean = mList.get(i);
viewHolder.imageView.setImageResource(mList.get(i).ItemImageResid);
viewHolder.title.setText(bean.ItemTitle);
viewHolder.content.setText(bean.ItemContent);
long end = System.nanoTime();
long dValue = end - start;
mSumTime += dValue;
Log.i("233", String.valueOf(mSumTime));
return convertView;
}
//避免重复的findViewById操作
class ViewHolder {
public ImageView imageView;
public TextView title;
public TextView content;
}
}