Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

java - Why using XML to create GUI is a good practice in Android

I am from Java Swing background. May I know why using XML to create GUI is a good practice in Android? For instance, instead of writing the code in (Which makes me feel more comfortable with it as I use to Swing desktop application)

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloAndroid extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       TextView tv = new TextView(this);
       tv.setText("Hello, Android");
       setContentView(tv);
   }
}

We write the code in XML way.

import android.app.Activity;
import android.os.Bundle;

public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

In tutorial, it states that,

This structure makes it very easy to quickly build up UIs, using a more simple structure and syntax than you would use in a programmatic layout.

However, I don't really buy the idea, as I feel that creating a separate XML file is more cumbersome.

Can anyone give a real world example (in the sense of Android), why using XML to build GUI is more superior than bare Java code?

If GUI programming through XML is really a good stuff, why it still hasn't become a common practice among GUI desktop application developers?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using XML layouts has many advantages over Java code. You get easy references to strings, drawables, dimensions, themes, etc. But the biggest advantage is automatic support for multiple configurations. Without changing your code you can have different layouts for landscape and portrait by just having an XML layout in layout-land/ and layout-port/. And you can do the same to adapt the layout to different resolutions, languages, etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...