1. 程式人生 > >ListView的優化

ListView的優化

systems who == 文件 generated add protected @override itemid

**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;
    }
}

ListView的優化