BaseAdapter 运用和优化

看完别人使用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。

结合别人代码,加上自己一点小理解。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值