关于ListView和Adapter

未优化的Adapter

import java.util.List;

import ouc.sei.proandroid.R;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MyAdapter2 extends BaseAdapter {
	private List<String> lists;
	private Context context;

	public MyAdapter2(List<String> lists, Context context) {
		this.lists = lists;
		this.context = context;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return lists.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return lists.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
		TextView textView;
		
		 int type = getItemViewType(position);
         System.out.println("getView " + position + " " + convertView + " type = " + type);
		
		convertView = View.inflate(context, R.layout.list_item, null);
		textView = (TextView) convertView.findViewById(R.id.textView);
		convertView.setTag(textView);
		textView.setText(lists.get(position));
		return convertView;
	}

}

这个Adapter对Item的每次请求都想getView请求生成一个convertView实例以返回。也就是说,如果有1亿个item,那么每次页面翻滚到这个Item时,convertView都会生成一个实例View,这样的代码是非常的耗内存的。

优化代码如下:

import java.util.List;

import ouc.sei.proandroid.R;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter {
	
	private List<String> lists;
	private Context context;
	public MyAdapter(List<String> lists,Context context){
		this.lists = lists;
		this.context = context;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return lists.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return lists.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
		TextView textView;
		
		 int type = getItemViewType(position);
         System.out.println("getView " + position + " " + convertView + " type = " + type);
         
		if (convertView == null){
			convertView = View.inflate(context, R.layout.list_item, null);
			textView = (TextView) convertView.findViewById(R.id.textView);
			convertView.setTag(textView);
		} else {
			textView = (TextView) convertView.getTag();
		}
		
		textView.setText(lists.get(position));
		return convertView;
	}

}
以上代码使用了复用的思想,首次请求时,首先显示一屏幕的Item,并建立实例,当Item1消失,Item10出现,则Item10会复用Item1的实例。如图:

关于ListView和Adapter_第1张图片
参考:http://android.amberfog.com/?p=296




你可能感兴趣的:(关于ListView和Adapter)