viewholder的使用

Adapter的作用就是ListView界面与数据之间的桥梁,当列表里的每一项显示到页面时,都会调用Adapter的getView方法返回一个View。 

优化的思路两种: 

1. View的重用 
    View的每次创建是比较耗时的,因此对于getview方法传入的convertView应充分利用 != null的判断 

2.ViewHolder的应用 

View的findViewById()方法也是比较耗时的,因此需要考虑只调用一次,之后就用View.getTag()方法来获得ViewHolder对象。 

下面是优化后的代码供参考: 

public class MyAdapter extends BaseAdapter {
	private Context mContext;
	private LayoutInflater mInflater;

	public MyAdapter(Context context) {
		this.mContext = context;
		mInflater = LayoutInflater.from(mContext);
	}

	public int getCount() {
		return mmsList.size();
	}

	public Object getItem(int arg0) {
		return arg0;
	}

	public long getItemId(int arg0) {
		return arg0;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = mInflater.inflate(R.layout.mmslistitem, null);
			holder.img = (ImageView) convertView.findViewById(R.id.mmsflag);
			holder.subject = (TextView) convertView
					.findViewById(R.id.mmssubject);
			holder.date = (TextView) convertView.findViewById(R.id.mmsdate);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		MMSDBItem mmsItem = mmsList.get(position);
		holder.subject.setText(mmsItem.getSubject());
		String today = DateFormat.format("yyyy-MM-dd",
				System.currentTimeMillis()).toString();
		String dateStr = DateFormat.format("yyyy-MM-dd kk:mm",
				mmsItem.getDate()).toString();
		holder.date.setText(dateStr);
		if (mmsItem.getFlag() == 0) {
			holder.img.setBackgroundResource(R.drawable.new_message_32);
		} else {
			holder.img
					.setBackgroundResource(R.drawable.message_already_read_32);
		}
		return convertView;
	}

	public final class ViewHolder {
		public ImageView img;
		public TextView subject;
		public TextView date;
	}
}


你可能感兴趣的:(viewholder的使用)