Salar de Uyuni – Bolivia

2013-03-31-2816

 

Advertisements

Android Code Snippets: Improving Layout Performance

A common task in Android development, is to call the findViewById() method in your adapters.
There is a repeated use of findViewById() in each cycle, because you need to look up all the elements and update them. This can be really slow in you have hundreds of elements to show, therefore the performance is affected.

What you usually do when start working with adapters is the following:

    public View getView(final int position, View convertView, ViewGroup parent) {
        convertView = inflater.inflate(R.layout.artist_item, null);
        ImageView artistImageView = (ImageView) convertView.findViewById(R.id.artist_image);
        TextViewartistNameTextView = (TextView) convertView.findViewById(R.id.artist_name);
		
        ...Update your views
		
        return convertView;
    }

Instead, use the View Holder design pattern. This will avoid to look the views up in each cycle.

First, you need to create a ViewHolder class and group your views inside it.
Then, in your getView method, match your viewHolder elements with your views in the layout.
Finally, update your views content.

    // Hold the views
    static class ViewHolder {
        ImageView artistImageView;
        TextView artistNameTextView;
    }

    // Populate viewHolder views and set up their content.
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.artist_item, null);
            viewHolder = new ViewHolder();
            viewHolder.artistImageView = (ImageView) convertView.findViewById(R.id.artist_image);
            viewHolder.artistNameTextView = (TextView) convertView.findViewById(R.id.artist_name);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        ...Update your views here

        return convertView;
    }