Dynamic vs XML layout in Android?

David Kroukamp picture David Kroukamp · Aug 14, 2012 · Viewed 14.7k times · Source

I'm new to Android development and have started creating my own UI. I see that you can either create it dynamically something like this (Dynamic Layouts):

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ScrollView sv = new ScrollView(this);
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    sv.addView(ll);
    TextView tv = new TextView(this);
    tv.setText("Name");
    ll.addView(tv);
    EditText et = new EditText(this);
    ll.addView(et);
    Button b = new Button(this);
    b.setText("Ok");
    ll.addView(b);
}

but I also see that netbeans has a file Resources->layout->main.xml. So you can create an XML layout for the UI (Declaring XML layout):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Hello World, AndroidTest"
    />
</LinearLayout>

So my question is which should I use? what is recommended and what are the pros/cons of dynamic vs XML layouts in Android development?

Answer

CommonsWare picture CommonsWare · Aug 14, 2012

Use layout XML resource files.

First, the resource sets (e.g., res/layout-land/ in addition to res/layout/) allow you to define multiple UIs to be used in different circumstances, with the system automatically choosing the right one as needed. The equivalent in Java would be one nasty set of if or switch statements.

Second, there are tools that can help you create those layout resources successfully. Even if the drag-and-drop GUI building of Eclipse isn't your cup of tea (e.g., you're using NetBeans), Lint will help point out flaws in your layouts, for which it will point out only a subset in the equivalent Java code.

Third, it tends to be more terse, so if you're typing this stuff by hand, the XML will be less typing.

Fourth, approximately 98% of all sample code you will find will use layout XML files, and approximately 98% of all UI answers you find here on StackOverflow (and other support resources) will assume that you use layout XML files. While you are free to avoid XML -- perhaps you were attacked by angle brackets as a young child or something -- you will be swimming upstream, fighting the current compared to what most Android developers do.