To understand the relationship between the two, I need to first clarify one thing. You say that "Button
inside XML is a view, but Button
inside Java is a class" which is true but a bit narrow. A Button
in XML is not just a View
but it's also a class.
View
is a Java class. Button
is a subclass of View
. The layout XML in Android is just a simple way to arrange a number of View
objects to form a UI. Anything you do in a layout XML can be done in Java code and it can accomplish the exact same thing. Android has these layout XMLs to simplify the process.
Consider the following example. These two scenarios will create the exact same UI.
Create UI with layout XML:
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black" >
<LinearLayout android:id="@+id/left_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MainActivity.java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Create UI in Java code:
MainActivity.java
public static final int LEFT_CONTAINER = 0x0710001B;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout parent = new LinearLayout(this);
parent.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
parent.setBackgroundColor(getResources().getColor(android.R.color.black));
LinearLayout child = new LinearLayout(this);
child.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
child.setId(LEFT_CONTAINER);
parent.addView(child);
setContentView(parent);
}
Now this is a very simple layout so the required code for each method is relatively light. If we scale this up to a UI with multiple containers and multiple controls, the Java code method starts to get really cluttered and prone to error. You're also creating the possibility for multiple dependencies on your MainActivity
class since it's holding the IDs of the layouts within it.
By using the layout XML, you confine the majority of your layout issues to one separate file and you reduce the amount of code that needs to be written to create your UI as the Android Activity
parent class will handle all of that for you. Additionally, you can reduce cross dependencies by having all of your layout and view IDs confined to your R
class that Android generates for identifiers.