***ListView优化
*优化一:因为getView()方法中每次都将布局重新加载了一遍,所以当ListView快速滚动的时候会影响效率
解决方法:可利用convertView参数将之前加载好的布局缓存
*优化二:在getView()方法中每次都要调用View的findViewById()方法获取一次控件的实例
解决方法:可通过新增一个类,用于对控件实例的缓存
public class MainActivity extends Activity {
private ListView lv;
private List<String> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lv);
list = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
list.add("item"+i);
}
MyAdapter adapter = new MyAdapter();
lv.setAdapter(adapter);
}
class MyAdapter extends BaseAdapter{
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.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) {
ViewHolder holder = null;
if(convertView==null){
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);//获得布局填充器对象
convertView = inflater.inflate(R.layout.item_test, null); //将item_test这个xml布局文件实例化成对应的view对象
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.id.tv);
convertView.setTag(holder);//利用setTag()方法对可复用的holder添加标记方便获取
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.tv.setText(list.get(position));
return convertView;
}
}
//新定义一个内部类,用于对控件的实例进行缓存
static class ViewHolder{
TextView tv;
}
}