Thursday, October 25, 2012

Previewing Your Views

Working with complicated view hierarchies in Android can be a pain. Countless times I've found myself in the debugger hunting through LinearLayouts searching for the right RadioButton to toggle, or trying to figure out whether some TextView has gotten added at the right spot.

Robolectric to the rescue!

Hey, here's a thing! Call Robolectric.dump(view) on some view object, and Robolectric will spew some XML to System.out describing that view and its children:

Robolectric.dump(view) (to System.out):
    <EditText id="id/street"/>
    <EditText id="id/apartment"/>
    <LinearLayout id="id/city_state_row" visibility="GONE">
      <Spinner id="id/city_picker" visibility="GONE"/>
      <EditText id="id/city" visibility="GONE" text="Toronto"/>
      <StateEditor id="id/province" visibility="GONE" text="ON"/>
    <LinearLayout id="id/postal_country_row">
      <EditText id="id/postal" text="M4Y 1D2"/>
      <TextView id="id/country_picker" text="Canada"/>

Another handy method returns any text contained within a view. If multiple TextViews are inside a layout, their text will be appended together:

Robolectric.innerText(view) returns:
  M4Y 1D2 Canada

Note that "Toronto" and "ON" didn't appear because they weren't visible.

Note: you'll need the latest source or the latest maven 1.2-SNAPSHOT.