Saturday 16 July 2011

Android User Interface: Using Xml layout resources Part 1

Problem: Getting a layout in xml, to bring it up on an activity. 

In android Views are widgets or controls like textviews, buttons, lists and the like. Activity is what you see on the screen i.e your window or frame that is to be displayed. Layout is how you arrange / position your views on the screen. This is similar to java layouts.


The first thing to do is to get your layout defined in an xml layout resource. This can easily be done by using the tools in eclispe for android development. Either you define the xml as shown below in hand or you can use the graphical editor. 

In the xml file below, there is a textview that acts as a banner and a listview. The attributes of the views are mostly straight forward. We can get more control over the views using these attributes. For the time being we focus on getting this xml layout on the screen.
The second step is to represent layout in code using a class which is subclassed from android.widget.LinearLayout. We will use this class in code to build the layout and the views in it (inflate) at runtime. 

(i) Define a class that extends from android.widget.LinearLayout
(ii) Define fields in the class for the textview and listview. For an instance of    this layout class we will get the corresponding view objects into these.
(iii) Override the Constructor for the view, place a call to the super class constructor. Now we add the code to inflate the xml layout. 
(iv) Inflating the layout is done using a system service in android called layout inflator service. Once we inflate the layout we get a reference to the textview and the listview of this layout by calling the findViewById method.

So far the layout is there to be used on an activity. To use this layout class in an activity,

(i) Declare this layout object in your activity.
(ii) In the onCreate method of this activity create the layout object using the current activity as context.
(iii) Set the layout using the 'setContentView' method.

You can set some values for the text view and the list view after this or in the layout class itself. Here an arrayadapter is used to set values to the listview. 

The advantage of using the xml layout is that, you dont build the layout in code and keep you user interface decoupled from the code. When the layout inflator inflates the layout, it can determine the best by using the xml attributes.

** Note:  Never forget to list your own new activities into the android manifest.

No comments: