看完别人使用BaseAdapter,发现之前自己使用的方法上还是有很多不足的,最明显就是没有对ListView进行优化。
public class RecentAdapter extends BaseAdapter {
private class ViewHolder {
TextView appName;
ImageView appIcon;
TextView appSize;
}
private List<ResolveInfo> mAppList;
private LayoutInflater mInflater;
private PackageManager pm;
public RecentAdapter(Context c, List<ResolveInfo> appList,
PackageManager pm) {
mAppList = appList;
this.pm = pm;
mInflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void clear(){
if(mAppList!=null){
mAppList.clear();
}
}
public int getCount() {
return mAppList.size();
}
@Override
public Object getItem(int position) {
return mAppList.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.app_info_item, null);
holder = new ViewHolder();
holder.appName = (TextView) convertView.findViewById(R.id.app_name);
holder.appIcon = (ImageView) convertView
.findViewById(R.id.app_icon);
holder.appSize = (TextView) convertView.findViewById(R.id.app_size);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ResolveInfo appInfo = mAppList.get(position);
if (appInfo != null) {
String labelName = appInfo.loadLabel(pm).toString();
if (labelName != null) {
holder.appName.setText(labelName);
}
Drawable icon = appInfo.loadIcon(pm);
if (icon != null) {
holder.appIcon.setImageDrawable(icon);
}
}
return convertView;
}
public void remove(int position){
mAppList.remove(position);
this.notifyDataSetChanged();
}
}
新建一个内部类ViewHolder,用于存放每个Listview中的item的组件。
当然这也是为了之后优化ListView 作准备。
而setTag()方法是给view 一个标志,方便下次取view 的时候通过标签去查,而不是view的视图结构去查,这样提高了查询的效率。
notifyDataSetChanged()方法是告诉View有数据变更,需要刷新Listview。
结合别人代码,加上自己一点小理解。