Fancy ListViews, Part Three PDF Print E-mail

In our last episode, we saw how we could save processing time — and, hence, battery life — by recycling existing row views in our fancy lists, simply by checking and reusing the convertView parameter passed into our getView().

In his comment to this series’ initial post, Romain Guy also left a bit of code that uses something called ViewHolder. Today, let’s take a look at this technique, with a twist.

The goal, once again, is to reduce the amount of work it takes to render one of our fancy lists, both so users get snappier response and so we don’t drain the battery so quickly. Recycling views saves us constructing new rows from whole cloth, particularly important when we are using ViewInflate and creating them from an XML layout.

Another somewhat expensive operation we do a lot with fancy views is call findViewById(). This dives into our inflated row and pulls out widgets by their assigned identifiers, so we can customize the widget contents (e.g., change the text of a TextView, change the icon in an ImageView). Since findViewById() can find widgets anywhere in the tree of children of the row’s root View, this could take a fair number of instructions to execute, particularly if we keep having to re-find widgets we had found once before.

In some GUI toolkits, this problem is avoided by having the composite Views, like our rows, be declared totally in program code (in this case, Java). Then, accessing individual widgets is merely the matter of calling a getter or accessing a field. And you can certainly do that with Android, but the code gets rather verbose. What would be nice is a way where we can still use the layout XML yet cache our row’s key child widgets so we only have to find them once.

That’s where ViewHolder comes in…or, in this post, a variation I’m calling ViewWrapper.

All View objects have getTag() and setTag() methods. These allow you to associate an arbitrary object with the widget. What the holder pattern does is use that “tag” to hold an object that, in turn, holds each of the child widgets of interest. By attaching that holder to the row View, every time we use the row, we already have access to the child widgets we care about, without having to call findViewById() again.

So, let’s take a look at one of these holder classes:

 
  1. class ViewWrapper { 
  2.     View base; 
  3.     TextView label=null
  4.     ImageView icon=null
  5.  
  6.     ViewWrapper(View base) { 
  7.         this.base=base; 
  8.     } 
  9.  
  10.     TextView getLabel() { 
  11.         if (label==null) { 
  12.             label=(TextView)base.findViewById(R.id.label); 
  13.         } 
  14.  
  15.         return(label); 
  16.     } 
  17.  
  18.     ImageView getIcon() { 
  19.         if (icon==null) { 
  20.             icon=(ImageView)base.findViewById(R.id.icon); 
  21.         } 
  22.  
  23.         return(icon); 
  24.     } 

The main difference between ViewWrapper (shown above) and ViewHolder (shown in the comment to this post) is that ViewWrapper lazy-finds the child widgets. If you create a wrapper and never need a specific child, you never go through the findViewById() operation for it and never have to pay for those CPU cycles. On the flip side, ViewHolder has the child widgets in public fields, whereas ViewWrapper uses getter methods, so there are going to be situations where a ViewHolder approach is more efficient.

The holder pattern also:

  • Allows us to consolidate all our per-widget type casting in one place, rather than having to cast it everywhere we call findViewById()

  • Perhaps track other information about the row, such as state information we are not yet ready to “flush” to the underlying model — more on this in an upcoming post

Using ViewWrapper is a matter of creating an instance whenever we inflate a row and attaching said instance to the row View via setTag(), as shown in this rewrite of last post’s demo’s getView() method:

 
  1. public View getView(int position, View convertView, ViewGroup parent) { 
  2.     View row=convertView; 
  3.     ViewWrapper wrapper=null
  4.  
  5.     if (row==null) { 
  6.         ViewInflate inflater=context.getViewInflate(); 
  7.  
  8.         row=inflater.inflate(R.layout.row, null, null); 
  9.         wrapper=new ViewWrapper(row); 
  10.         row.setTag(wrapper); 
  11.     } 
  12.     else
  13.         wrapper=(ViewWrapper)row.getTag(); 
  14.     } 
  15.  
  16.     wrapper.getLabel().setText(getModel(position)); 
  17.  
  18.     if (getModel(position).length()>4) { 
  19.         wrapper.getIcon().setImageResource(R.drawable.delete); 
  20.     }    
  21.  
  22.     return(row); 

Just as we check convertView to see if it is null in order to create the row Views as needed, we also pull out (or create) the corresponding row’s ViewWrapper. Then, accessing the child widgets is merely a matter of calling their associated methods on the wrapper.

Many thanks to Romain Guy for pointing out this technique!

In our next episode, we’ll look at putting interactive widgets in a row, not just static ones like TextView and ImageView, and discuss making modifications to the state that supplies the data for the list itself.

 

 

Source: http://androidguys.com/2008/07/22/fancy-listviews-part-three/

Comments (18)Add Comment
tiffany on sale
written by tiffany on sale , May 22, 2010
GOOD
Many thanks to Romain Guy for pointing out this technique!
report abuse
vote down
vote up
Votes: +0
birkenstock shoes
written by birkenstock , May 29, 2010
When you are on a holiday in some seaside resort where you will hike and walk on cliffs, Birckenstock is one of the brands to which you turn your attention to find some slippers or flip-flops that make a holiday in comfort and without pain in the feet after a romantic walk on the rocks.Birkenstocks is the well-known German footwear brand: Birkenstock shoes, Birkenstock sandals and Birkenstock clogs.Birkenstock Gizeh is a flattering flip-flop style with a leather upper that will look great with shorts, jeans or dresses, at the same time, it has an irresistible air between the tourist and hiking, and you can be sure that the evening will have no pain, given the high quality these shoes.
report abuse
vote down
vote up
Votes: +0
...
written by supra shoes , May 31, 2010
The are popular with both recreation and Supra Shoes
Supra Footwear sportswear are simply matchless in terms of style, comfort and longevity, Now! Free Shipping! NO Tax!
report abuse
vote down
vote up
Votes: +0
air max 2009
written by air max 2009 , May 31, 2010
are you looking for a air max 2009?
here are not only offer the nike free shoes ,but aslo for thenew lebron VII shoes
report abuse
vote down
vote up
Votes: +0
vvvvvvvvvvvv
written by dsf , June 12, 2010
香港網頁寄存服務
香港網頁設計公司
香港域名註冊
香港服务器租用
香港服务器出租
香港主机租用
香港網頁設計

report abuse
vote down
vote up
Votes: +0
...
written by liu , June 12, 2010
The louis vuitton online store has gotten the 2010 hot new products. Discount LV handbag on sale and cheap Louis Vuitton replica handbags are ...louis vuitton
lv
vitton
replica handbags
report abuse
vote down
vote up
Votes: +0
...
written by mbt , June 18, 2010
The are popular with both recreation
report abuse
vote down
vote up
Votes: +0
ds
written by louis vuitton , June 19, 2010
Buy gucci handbags, gucci bags, gucci wallets, prada handbags, prada bags, prada wallets,
louis vuitton, Louis Vuitton replica, vitton ..lv
replica handbags
report abuse
vote down
vote up
Votes: +0
this problem is avoided
written by coach outlet , June 19, 2010
this problem is avoided by having the composite Views, like our rows, be declared totally in program code (in this case, Java). Then, accessing individual widgets is merely the matter of calling a getter or accessing a field.
report abuse
vote down
vote up
Votes: +0
v
written by louis vuitton , June 23, 2010
Buy gucci handbags, gucci bags, gucci wallets, prada handbags, prada bags, prada wallets,
louis vuitton, Louis Vuitton replica, vitton ..lv
replica handbags
report abuse
vote down
vote up
Votes: +0
Cheap San Francisco 49ers Jerseys
written by sexy bikinis , June 24, 2010
It is not the NFL Jerseys critic who counts,not the man who points out how the strong man stumbles,the doer of deeds could have sexy bikinis sale done them better. The credit belongs to the man who is actually in the arens,whose face is marred by dust and sweat and blood.
report abuse
vote down
vote up
Votes: +0
...
written by Tiffany jewelry , June 28, 2010
A biker was riding along a California beach when suddenly the sky clouded above his head and, in a booming voice, the Lord said, "Because you have TRIED to be faithful to me in all ways, I will grant you one wish." The biker pulled over and said, "Build a bridge to Hawaii so I can ride over anytime I want."Tiffany Jewelry] | replica watches
report abuse
vote down
vote up
Votes: +0
mbt
written by mbt shoes , June 29, 2010
The credit belongs to the man who is actually in the arens,whose face is marred by dust and sweat and blood.
vibram kso
report abuse
vote down
vote up
Votes: +0
christian louboutin
written by louboutin shoes , July 08, 2010

christian louboutin sandals
christian louboutin pumps
report abuse
vote down
vote up
Votes: +0
Cheap GHDs
written by Cheap GHDs , July 17, 2010
Cheap ghds is is provided purely as an information based service.
Cheap GHDs
We provide information, specification, and price comparisons of ghd products, both promoting them and helping you find the best online prices from reputable retailers bringing you the cheapest ghds online.
GHD Straighteners
We try to ensure that information on this website is as accurate as possible,
GHD Colour Collection
however we accept no responsibility for any errors on this website whatsoever. This website is updated throughout the day,
GHD IV Styler
every day to ensure that the information you see is as accurate as possible.
GHD Precious Gift Set
This site is in no way owned by or affiliated with ghd and is an unofficial ghd price comparison website.
GHD IV Styler Dark
All images, logos and trademarks belong to their respective owners.
GHD Radiance Benefit Set
By using this website you are agreeing to our Privacy policy and Terms & Conditions.
GHD Hair Straightener
GHD on sale
GHD IV Salon Styler
GHD IV Mini Styler
GHD IV Gold Styler
GHD Kiss IV Styler
GHD Pure IV Styler
GHD Purple IV Styler
GHD Black IV Styler
GHD Benefit Styler
GHD Rare Styler
GHD Pink Styler
report abuse
vote down
vote up
Votes: +0
timberland mens roll top
written by timberland mens roll top , July 27, 2010
Here was someone immersed in a search for truth and beauty. Words had been cheap timberland boots treasured, words that were beautiful. And I felt as if the words timberland waterproof boots somehow delighted in being discovered, for they were obviously very generous to the as yet anonymous writer of the notes. And now this person was in turn learning the secret of sharing them. Beauty so shines when given away.
report abuse
vote down
vote up
Votes: +0
Monster Energy Hats
written by Monster Energy Hats , July 28, 2010
I don’t know what to say except that I have enjoyed
reading.Nice blog,I will keep visiting this blog very often.
report abuse
vote down
vote up
Votes: +0
...
written by Abercrombie fitch outlet , July 28, 2010
IV Styler
GHD Purple IV Styler
GHD Black IV Styler
GHD Benefit Styler
GHD Rare Styler
GHD Pink Styler
report abuse
vote down
vote up
Votes: +0

Write comment
quote
bold
italicize
underline
strike
url
image
quote
quote
smile
wink
laugh
grin
angry
sad
shocked
cool
tongue
kiss
cry
smaller | bigger

security code
Write the displayed characters


busy
 

 

This domain is for sale! Please contact me via contact page!