Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of using xml for layout?

I've been through a few tutorials etc and have found that I can acheive the same results defining all of my UI components in code.

For example:

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    TextView tv = new TextView(this);
    tv.setText("hello");
    LinearLayout ll = new LinearLayout(this);
    ll.addView(tv);
    setContentView(ll);
}

is the equivalent of

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

+

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="@string/hello"/>

What are the performance/maintainability benefits of using XML for this?

If a programmer prefers to use code over XML what extra considerations should be made?

like image 700
pstanton Avatar asked Dec 06 '22 20:12

pstanton


2 Answers

What are the maintainability benefits of using XML for this?

  1. Separation of logic from presentation. This does help on larger projects when you need to refactor some code. If it is tightly coupled to the UI this job can become time consuming very easily if much of the presentation logic is in code.
  2. The structure of XML correlates nicely to the structure of a user interface, i.e., a tree like structure.

What are the performance benefits of using XML for this?

That all depends on the implementation I suppose. I doubt there are any appreciable performance differences, but I honestly don't know enough to say definitively what they may be.

like image 63
Ed S. Avatar answered Jan 10 '23 22:01

Ed S.


You may refer to Why using XML to create GUI is a good practice in Android.

For me, I feel this is more like personal taste. I came from Java Swing background. When I am doing desktop app development, I prefer to create GUI programmatic.

However, when comes to Android development, I will stick to XML based GUI development, although I favour to use code instead of XML.

This is because, I tend to follow the majority favoured coding style and mythology, which makes me easy to get technical support and tutorials.

like image 32
Cheok Yan Cheng Avatar answered Jan 10 '23 22:01

Cheok Yan Cheng