Fancy ListViews, Part One PDF Print E-mail

The classic Android ListView is a plain list of text — solid but uninspiring. This is the first in a series of posts where we will see how to create a ListView with a bit more pizazz. Today, in particular, we will see two techniques for creating a ListView whose rows contain icons, in addition to text.

If you want rows to have a different look than the stock rows, one way to accomplish this is to supply your own layout XML to be used for each row, telling Android to use your layout rather than one of the built-in ones. This gives you complete control over what goes in the row and how it is laid out.

 

For example, suppose you want a ListView whose entries are made up of an icon, followed by some text. You could construct a layout for the row that looks like this:

 
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     android:layout_width="fill_parent" 
  3.     android:layout_height="wrap_content" 
  4.     android:orientation="horizontal" 
  5. > 
  6.     <ImageView 
  7.         android:id="@+id/icon" 
  8.         android:layout_width="22px" 
  9.         android:paddingLeft="2px" 
  10.         android:paddingRight="2px" 
  11.         android:paddingTop="2px" 
  12.         android:layout_height="wrap_content" 
  13.         android:src="@drawable/ok" 
  14.     /> 
  15.     <TextView 
  16.         android:id="@+id/label" 
  17.         android:layout_width="wrap_content" 
  18.         android:layout_height="wrap_content" 
  19.         android:textSize="44sp" 
  20.     /> 
  21. </LinearLayout> 

This layout uses a LinearLayout to set up a row, with the icon on the left and the text (in a nice big font) on the right.

By default, though, Android has no idea that you want to use this layout with your ListView. To make the connection, you need to supply your Adapter with the resource ID of your custom layout:

 
  1. public class StaticDemo extends ListActivity { 
  2.     TextView selection; 
  3.     String[] items={"lorem", "ipsum", "dolor", "sit", "amet"
  4.                     "consectetuer", "adipiscing", "elit", "morbi", "vel"
  5.                     "ligula", "vitae", "arcu", "aliquet", "mollis"
  6.                     "etiam", "vel", "erat", "placerat", "ante"
  7.                     "porttitor", "sodales", "pellentesque", "augue"
  8.                     "purus"}; 
  9.  
  10.     @Override 
  11.     public void onCreate(Bundle icicle) { 
  12.         super.onCreate(icicle); 
  13.         setContentView(R.layout.main); 
  14.         setListAdapter(new ArrayAdapter(this
  15.                                     R.layout.row, R.id.label, 
  16.                                     items)); 
  17.         selection=(TextView)findViewById(R.id.selection); 
  18.     } 
  19.  
  20.     public void onListItemClick(ListView parent, View v,int position, long id) { 
  21.         selection.setText(items[position]); 
  22.     } 

This example, derived from one of the ones in my book, displays a list of random words, and puts the currently-selected word in a TextView.

The key in this example is that you have told ArrayAdapter that you want to use your custom layout (R.layout.row) and that the TextView where the word should go is known as R.id.label within that custom layout.

The result is a ListView with icons down the left side. In particular, all the icons are the same.

This technique — supplying an alternate layout to use for rows — handles simple cases very nicely. However, it falls down when you have more complicated scenarios for your rows, such as:

  • Not every row uses the same layout (e.g., some have one line of text, others have two)

  • You need to configure the widgets in the rows (e.g., different icons for different cases)

In those cases, the better option is to create your own subclass of your desired Adapter, override getView(), and construct your rows yourself. The getView() method is responsible for returning a View, representing the row for the supplied position in the adapter data.

For example, let’s rework the above code to use getView(), so we can have different icons for different rows — in this case, one icon for short words and one for long words:

 
  1. public class DynamicDemo extends ListActivity { 
  2.     TextView selection; 
  3.     String[] items={"lorem", "ipsum", "dolor", "sit", "amet"
  4.                 "consectetuer", "adipiscing", "elit", "morbi", "vel"
  5.                 "ligula", "vitae", "arcu", "aliquet", "mollis"
  6.                 "etiam", "vel", "erat", "placerat", "ante"
  7.                 "porttitor", "sodales", "pellentesque", "augue"
  8.                 "purus"}; 
  9.  
  10.     @Override 
  11.     public void onCreate(Bundle icicle) { 
  12.         super.onCreate(icicle); 
  13.         setContentView(R.layout.main); 
  14.         setListAdapter(new IconicAdapter(this)); 
  15.         selection=(TextView)findViewById(R.id.selection); 
  16.     } 
  17.  
  18.     public void onListItemClick(ListView parent, View v, int position, long id) { 
  19.         selection.setText(items[position]); 
  20.     } 
  21.  
  22.     class IconicAdapter extends ArrayAdapter { 
  23.         Activity context; 
  24.  
  25.         IconicAdapter(Activity context) { 
  26.             super(context, R.layout.row, items); 
  27.  
  28.             this.context=context; 
  29.         } 
  30.  
  31.         public View getView(int position, View convertView, ViewGroup parent) { 
  32.             ViewInflate inflater=context.getViewInflate(); 
  33.             View row=inflater.inflate(R.layout.row, null, null); 
  34.             TextView label=(TextView)row.findViewById(R.id.label); 
  35.  
  36.             label.setText(items[position]); 
  37.  
  38.             if (items[position].length()>4) { 
  39.                 ImageView icon=(ImageView)row.findViewById(R.id.icon); 
  40.  
  41.                 icon.setImageResource(R.drawable.delete); 
  42.             }    
  43.  
  44.             return(row); 
  45.         } 
  46.     } 

In our getView() implementation, we first get our hands on a ViewInflate object, as described in the previous Building ‘Droids post, so we can use it to “inflate” our row layout XML and give us a View representing that row.

Then, we tailor that View to match our needs:

  • We fill in the text label into our label widget, using the word at the supplied position

  • We see if the word is longer than four characters and, if so, we find our ImageView icon widget and replace the stock resource with a different one

Now, we have a ListView with different icons based upon context of that specific entry in the list. Obviously, this was a fairly contrived example, but you can see where this technique could be used to customize rows based on any sort of criteria, such as other columns in a returned Cursor.

Next time, we’ll take a closer look at the convertView parameter to our getView() method and see how we can make use of it to more efficiently render our list.

 

Source: http://androidguys.com/2008/07/14/fancy-listviews-part-one/

Comments (11)Add Comment
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: -1
...
written by jordan shoes , May 31, 2010
would a little more money make us a little happier? Many of us smirk and nod. There is, we believe, some connection between fiscal fitness and feeling fantasti air jordan shoes
. Most of us would say that, yes, we would like to DC. michael jordan shoes
Three in four American collegians now consider it.
report abuse
vote down
vote up
Votes: -1
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: -1
sexy bikini sotre
written by Ed Hardy swimwear , June 03, 2010
www.clothshoe.com/Bikini designer swimwear including Ed Hardy swimwear and tankinis, one piece sexy girl bikini, seperate bikini tops and bottons, plus size sexy swimwear bikini,and maternity swimwear, to kaftans, cover ups and summer dresses, beach hats and
report abuse
vote down
vote up
Votes: -1
...
written by mbt , June 18, 2010
The are popular with both recreation
report abuse
vote down
vote up
Votes: -1
suppose you ...
written by coach handbags , June 19, 2010
suppose you want a ListView whose entries are made up of an icon, followed by some text. You could construct a layout for
report abuse
vote down
vote up
Votes: +2
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: -1
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 cheap nfl jerseys arens,whose face is marred by dust and sweat and blood;who stives Ed Hardy Bikini valiantly;who errs,and comes short again and again;because there is not effort without Ralph Lauren Bikini error and shortcoming;but who does actually strive to do the Cheap San Francisco 49ers Jerseys deeds;who knows the great San Francisco 49ers Jerseys Sale enthusiasms,the great devotions;who spends himself in a worthy cause,who at the best sexy bikinis knows in the end the triumphs of high achievement and who at the NFL Dallas Cowboys Jerseys worst,if he fails,at least fails whiledaring greatly,so that his place shall never be with those cold and timid souls who know neither victory nor defeat. We encourage our Cheap Kobe Bryant Jerseys children to be competitive, to get ahead, to make money, to acquire possession. In games and in business alike, the aim is to win the game, the trophy, the contract. We go in for Sexy Ed Hardy Bikini laboursaving devices, gadgets, speed and shortcuts. We think every young couple should set up a home of their own.
report abuse
vote down
vote up
Votes: -1
...
written by mbt shoes , June 29, 2010
.We think every young couple should set up a home of their own.

vibram kso
report abuse
vote down
vote up
Votes: -1
...
written by nfl jerseys , July 27, 2010
ghd hair straighteners
ed hardy clotheswansantg1zxl
report abuse
vote down
vote up
Votes: +0
...
written by Abercrombie and fitch , July 29, 2010
timid souls who know neither victory nor defeat. We encourage our Cheap Kobe Bryant Jerseys children to be competitive, to get ahead, to make money, to acquire possession. In games and in business alike, the aim is to win the game, the trophy, the contract. We go in for Sexy Ed Hardy Bikini laboursaving devices, gadgets, speed and shortcuts. We think every young couple should set up a home of their own.
report abusevote downvote up
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!