Android开发之提高程序效率

ListView在Android程序中必不可少,ListView显示数据时通过Adapter来实现的
Adapter是ListView和Adapyer之间的中间人
当每条数据进入可见区域时,都会调用Adapter的getView返回这条数据的视图
getView的效率高低取决了ListView的效率
以下是几种方式分析:
1、最慢的方法,最简单最不实用

public View getView(int position, View convertView, ViewGroup parent) {
        View item = mInflater.inflate(R.layout.lib_item_list, null);
        TextView view = (TextView) item.findViewById(R.id.name);
        view.setText("hello world");
        return item;
}

2、利用convertView回收视图,效率提高 200%

public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null){
                convertView = mInflater.inflate(R.layout.lib_item_list, null);
        }
        TextView view = (TextView) convertView.findViewById(R.id.name);
        view.setText("hello world");
        return convertView;
}

3、利用ViewHolder模式,效率在提高 50%

public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if(convertView == null){
                convertView = mInflater.inflate(R.layout.lib_item_list, null);
                holder = new ViewHolder();
                holder.mName = (TextView) convertView.findViewById(R.id.name);
                convertView.setTag(holder);
        }else{
                holder = (ViewHolder) convertView.getTag();
        }
        holder.mName.setText("hello world");
        return convertView;
}
static class ViewHolder {
        TextView mName;
}

1

你可能感兴趣的:(Android开发)