ViewHolder Pattern
- ViewHolder design pattern is used to speed up rendering of your
ListView
- actually to make it work smoothly, findViewById is quite expensive (it does DOM - Data Object Model parsing) when used each time a list item is rendered, it must traverse our layout hierarchy and also instantiate objects. - Since lists can redraw its items quite frequently during scrolling such overhead might be substantial.
- The ViewHolder pattern is solely to reduce the number of view.findViewById(int) calls we make.
- The ViewHolder pattern only works when we take advantage of view recycling
- The ViewHolder design pattern enables you to access each list item view without the need for the look up, saving valuable processor cycles.
- Specifically, it avoids frequent call of findViewById() during ListView scrolling, and that will make it smooth
Without the ViewHolder Design Pattern
Okay, let’s dig it out and see how it works without the ViewHolder pattern.
Let’s take a look at our previous getView() method in ArrayAdapterItem.java
- The first time it was loaded, convertView is null. We’ll have to inflate our list item layout and find the TextView via findViewById().
- The second time it was loaded, convertView is not null, good! We don’t have to inflate it again. But we’ll use findViewById() again.
- The following times it was loaded, convertView is definitely not null. But findViewById() is constantly called, it will work but, it slows down the performance especially if you have lots of items and Views in your ListView.
With the ViewHolder Design Pattern
Now let’s see how it works with the ViewHolder pattern.
- The first time it was loaded, convertView is null. We’ll have to inflate our list item layout, instantiate the ViewHolder, find the TextView via findViewById() and assign it to the ViewHolder, and set the ViewHolder as tag of convertView.
- The second time it was loaded, convertView is not null, good! We don’t have to inflate it again. And here’s the sweet thing, we won’t have to call findViewById() since we can now access the TextView via its ViewHolder.
- The following time it was loaded, convertView is definitely not null. The findViewById() is never called again, and that makes our smooth ListView scrolling.
Comments
Post a Comment