Sunday, December 23, 2007

XML and programmatic layout

The tutorial taught me how to use XML files (under the layout directory) to define screen layouts. I was curious about the relationship of the XML layout and the Java classes like android.widget.LinearLayout. To verify it, I tried to recreate programmatically the layout of the skeleton project.

Update: download the project bundle from here.

The XML layout file of the skeleton project declares that the application's main view is controlled by a LinearLayout that occupies the entire available screen estate (fill_parent for both the layout_width and layout_height). The LinearLayout is vertical (elements are placed vertically). The layout contains just one text element that fills the entire available width (layout_width=fill_parent) but occupies just the height needed for the content (layout_height=wrap_content).

This XML file is inflated into instances of Java objects. The following code is equivalent in functionality with the XML file (except for the text of the TextView instance).

public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
TextView t = new TextView( this );
t.setText( "Hello, world, programmatic layout" );
LinearLayout.LayoutParams tlp =
new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT );
LinearLayout l = new LinearLayout( this );
l.setOrientation( LinearLayout.VERTICAL );
t.setPreferredWidth( LayoutParams.FILL_PARENT );
t.setPreferredHeight( LayoutParams.FILL_PARENT );
l.addView( t, tlp );
setContentView( l );
}

While playing with this example, I ran into an application error.



This error was a great opportunity to try out the adb logcat command which dumps the emulator's log. By browsing the blog, I was able to find the offending exception (excerpts):

E/AndroidRuntime( 634): at android.view.ViewGroup.addView(ViewGroup.java
:792)
E/AndroidRuntime( 634): at android.view.ViewGroup.addView(ViewGroup.java
:780)
E/AndroidRuntime( 634): at aexp.h2.H2.onCreate(H2.java:25)
E/AndroidRuntime( 634): at android.app.Instrumentation.callActivityOnCre
ate(Instrumentation.java:786)

6 comments:

Unknown said...

The adb logcat command is a useful tool. Thanks for highlighting it.

Gabor Paller said...

Wow, how did you find the blog? :-)

Unknown said...

I found your blog searching blogger for other Android developers.

I've started Shook Labs to research and develop advanced mobile applications. We are currently focusing on the Android platform and writing an application for Google's Android Developer Challenge.

Keep up the good work and hopefully we'll see your android application in the wild.

Gabor Paller said...

Note that I researched advanced mobile applications while at Nokia (not anymore :-))

Anonymous said...

How did you fix the errors? what do they mean?

Anonymous said...

awsome...