Programming and Personal Development

2 ways to structure the UI components in your android application

Structuring the UI Components in your android application  can be done in two ways:

  • Using code:  You can use java code to explicitly create and position the various UI components. If you have programmed desktop GUI applications in java using swing/AWT, this should be familiar to you.
  • Using xml layout files: You can also specify the components and their positions in  .xml files and place them as resources under the /res/layout directory. Android automatically generates a id for the layout resource using the Android Asset packaging tool (aapt)  which can then be referred in the java code to render the associated view.

The xml layout option is the preferred over directly creating the components in the code for 2 reasons:

  • It keeps the UI structure separate from the application logic
  • Its easier to read and modify for both programmers and GUI builder tools like that found in the IDEs such as Eclipse or Intellij.
Let us consider the simple example of rendering a button in the UI  using both approaches. In both cases the end result is a button that says “click Me”.
render a android button in the screen

Android Button render

For option 1, you can create a new  instance of the Button object and set that as the view to be rendered  for the activity.
// option 1:
public class ButtonActivity extends Activity {

    // Demo Button
    Button m_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // create the button and set a text for the button
        m_button = new Button(this);
        m_button.setText("Click Me");
        // make the button as the view for the activity
        setContentView(m_button);
    }
}
For option 2, as shown below, there are 2 components,  the xml layout file specifies the presence of a “Button” element and its position via the “LinearLayout” element.   The layout is then referenced in the corresponding java code using the “R.layout.buttonactivity” id generated by the aapt tool.
// option2 ( xml layout + java code)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <Button android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:text="Click Me"/>

</LinearLayout>

public class ButtonActivity extends Activity {

    // Demo Button
    Button m_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Set the the layout file as the view for the activity
        setContentView(R.layout.buttonactivity);
    }
}
Web Analytics