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)
0 comments:
Post a Comment