tommek

I just push the buttons….

Archive for the ‘Performance’ Category

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

%d bloggers like this: