ListView使用技巧(一):ViewHolder

使用ViewHolder模式提高效率:

ViewHolder模式充分利用ListView的视图缓冲机制,避免了每次在调用getView()的时候都去通过findViewById()实例化控件。

只需要在自定义Adapter中定义一个内部类ViewHolder,并将布局中的控件作为成员变量:

public final class ViewHolder{
      public ImageView img;
      public TextView title;
}

接下来只要在getView()方法中通过视图缓冲机制来重用以缓存即可。完整的代码如下:
public class ViewHolderAdapter extends BaseAdapter{

	private List<String> mData;
	private LayoutInflater mInflater;
	
	public ViewHolderAdapter(Context context, List<String> data)
	{
		this.mData = data;
		mInflater = LayoutInflater.from(context);
	}
	
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mData.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return mData.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ViewHolder holder = null;
		if(convertView == null)
		{
			holder = new ViewHolder();
			convertView = mInflater.inflate(R.layout.viewholder_item, null);
			holder.img = (ImageView) convertView.findViewById(R.id.imageView1);
			holder.title = (TextView) convertView.findViewById(R.id.textView1);
			convertView.setTag(holder);
			
		}else {
			holder = (ViewHolder) convertView.getTag();
			
		}
		holder.img.setBackgroundResource(R.drawable.ic_launcher);
		holder.title.setText(mData.get(position));
		return convertView;
	}

	public final class ViewHolder{
		public ImageView img;
		public TextView title;
	}
}
这样就是ViewHolder的用法!!!

你可能感兴趣的:(ListView使用技巧(一):ViewHolder)