ListView
中的Adapter
优化的通用模板。
如果发现对ListView
优化工作做完后,还会卡顿,可以检查notifyDataSetChanged()
方法是否运用合理,频繁的调用此方法也会引发卡顿。
1.构造函数的通用化
构造函数中的List不指定数据类型
public TemplateAdapter(Context context, List data) {
this.mContext = context;
this.mData = data;
}
2.创建 ViewHolder
// 使用ViewHolder
...
private static class ViewHolder {
private TextView tvTitle, tvContent;
private ImageView ivIcon;
}
...
3.非空判断
@Override
public int getCount() {
return null == mArrayList ? 0 : mArrayList.size();
}
4.getView中操作
getView中inflate
的两种方式:
// 方式一 推荐使用方式一,简介
convertView = View.inflate(mContext, R.layout.item_ad, null);
// 方式二
convertView = mInflater.inflate(R.layout.item_layout, parent, false);
Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
//判断是否有缓存
if (convertView == null || convertView.getTag == null) {
//通过LayoutInflate实例化布局
viewHolder = new ViewHolder();
//convertView = mInflater.inflate(R.layout.item_layout, parent, false);
convertView = View.inflate(mContext, R.layout.item_ad, null);
viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
viewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_content);
convertView.setTag(viewHolder);
} else {
//通过tag找到缓存的布局
viewHolder = (ViewHolder) convertView.getTag();
}
// 数据渲染
NewsBean newsBean = newsBeanList.get(position);
// 所有的字段必须做非空判断
String urlString = null == newsBean.newsIconUrl ? "" : newsBean.newsIconUrl;
viewHolder.ivIcon.setTag(urlString); // 将ImageView与url绑定
//普通异步加载
// mImageLoader.showImageByThread(viewHolder.ivIcon,urlString);
mImageLoader.showImageByAsyncTask(viewHolder.ivIcon,urlString);
viewHolder.tvTitle.setText(newsBean.newsTitle);
viewHolder.tvContent.setText(newsBean.newsContent);
return convertView;
}
5.完整的Adapter
模板
public class TemplateAdapter extends BaseAdapter {
private Context mContext;
// 加上