Thursday, March 4, 2010

Two-dimensional lists

I got another question whether TableLayout can be used like a two-dimensional ListView. My initial reaction was that it cannot be done because TableLayout just arranges items, all the complicated focusing/highlighting logic in ListView is completely missing from TableLayout. I realized later on, however, that TableLayout can contain Buttons and the rest will be arranged by the general focus handling logic in ViewGroup.

Click here to download the example program.

The only exciting part of this rather simple program is the way how an array of Buttons are made to look like selectable list items. The key is that the Buttons are styled. For example (XML fragments are mangled due to blog engine limitations):

[Button android:id="@+id/button_1"
style="@style/MyButton"
android:text="1"/]

The referred style is in res/values/styles.xml. The funny part is this line:

[item name="android:background"]@android:drawable/list_selector_background[/item]

This line was copied straight from the system style of List.View and applies the ListView selector (that defines appearance of list elements in ListView in their different states) to the Button. No wonder the Button behaves like a list element.

3 comments:

Jophrey said...

Nice! What's the definition for the style MyButton? Just curious.

Gabor Paller said...

jophrey, download the example program, it is in res/values/styles.xml

S. Morgan Biggs said...

Thank you! I have been looking (and experimenting) for something just like this. I only wish I'd've found this sooner!