tommek

I just push the buttons….

Improving your Android List Activity Performance with a ViewHolder

leave a comment »

I recently attended a Android developer lab at the Sydney Google offices. (ADL) Most of the day was about Android Market place etc but they did have one speaker Bill Laun who spoke about UI Best Practices & High Performance Apps. Most of the best practices talk was about design and graphics related to different screen sizes and dpi.

He did show us one thing that I found useful and had not heard of before and this was the “ViewHolder”. Using this strategy with your custom Adapter improves the performance for your List.

Every time your custom Adapter is executed the “getView()” method is called to get reference to your custom layout and populate it with data. If you have a large list, calling  “findViewById()” to access resource on every row will impact the performance of your list. So to get around this you can use a “ViewHolder” which basically keeps a object in memory with references to your row layout. This means you do not need to use “findViewById()”every time “getView()” is called but only once on the first call of it when the list is created.

public View getView(int position, View convertView, ViewGroup parent) {

		View v = convertView;
		ViewHolder holder;
        if (v == null) {

        	LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        	v = vi.inflate(R.layout.article_row, null);

        	 holder = new ViewHolder();
        	 holder.title = (TextView) v.findViewById(R.id.article_title);
        	 holder.description = (TextView) v.findViewById(R.id.article_des);
        	 holder.date = (TextView) v.findViewById(R.id.article_pubdate);
        	 v.setTag(holder);
        } else {
        	holder = (ViewHolder) v.getTag();
        }
        Article article = articles.get(position);
        if (article != null) {
        	holder.title.setText(article.title);
        	holder.description.setText(article.description);
        	holder.date.setText(article.pubDate);
        }
        return v;
}
class ViewHolder{
	TextView title;
	TextView description;
	TextView date;
}
Advertisements

Written by tomkaurin

November 8, 2010 at 4:42 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: