Android如何提高ListView的滑动效率

来源:互联网 发布:科比退役是网络直播吗 编辑:程序博客网 时间:2024/06/09 16:43
如何提高ListView的滚动速度,ListView的滚动速度的提高在于getView方法的实现,通常我们的getView方法会这样写:


[java] view plaincopy
  1. View getView(int position,View convertView,ViewGroup parent){  
  2.     //首先构建LayoutInflater  
  3.      LayoutInflater factory = LayoutInflater.from(context);  
  4.                   View view = factory.inflate(R.layout.id,null);  
  5.     //然后构建自己需要的组件  
  6.       TextView text = (TextView) view.findViewById(R.id.textid);  
  7.       .  
  8.       .  
  9.      return view;  
  10. }  


 

这样ListView的滚动速度其实是最慢的,因为adapter每次加载的时候都要重新构建LayoutInflater和所有你的组件.而下面的方法是相对比较好的:

[java] view plaincopy
  1. View getView(int position,View contertView,ViewGroup parent){  
  2.     //如果convertView为空,初始化convertView  
  3.      if(convertView == null)  
  4.        {  
  5.         LayoutInflater factory = LayoutInfater.from(context);  
  6.                    convertView = factory.inflate(R.layout.id,null);  
  7.        }  
  8.    //然后定义你的组件  
  9.      (TextView) convertView.findViewById(R.id.textid);  
  10.      return convertView;  
  11. }  


 

[html] view plaincopy
  1. 这样做的好处就是不用每次都重新构建convertView,基本上只有在加载第一个item时会创建convertView,这样就提高了adapter的加载速度,从而提高了ListView的滚动速度.而下面这种方法则是最好的:  
[java] view plaincopy
  1. //首先定义一个你 用到的组件的类:  
  2. static class ViewClass{  
  3.      TextView textView;  
  4.      .  
  5.      .  
  6. }  
  7.   
  8. View getView(int position,View convertView,ViewGroup parent){  
  9.      ViewClass view ;  
  10.       if(convertView == null){  
  11.          LayoutInflater factory = LayoutInflater.from(context);  
  12.                     convertView = factory.inflate(R.layout.id,null);  
  13.          view = new ViewClass();  
  14.          view.textView = (TextView)   
  15.                           convertView.findViewById(R.id.textViewid);  
  16.         .  
  17.         .  
  18.          convertView.setTag(view);  
  19.        }else{  
  20.           view =(ViewClass) convertView.getTag();  
  21. }  
  22. //然后做一些自己想要的处理,这样就大大提高了adapter的加载速度,从而大大提高了ListView的滚动速度问题.  
  23.   
  24. }  
0 0
原创粉丝点击