Layouts, Views, Widgets...all of them are Java objects, with methods to configure the element like in XML. If we have a deep look at the Android Reference Page:
http://developer.android.com/reference/android/widget/LinearLayout.html
(This is the reference for the LinearLayout).
We can see the XML attributes (Inherited XML Attributes) of this element, and its related method in Java code. For example, for the “gravity” attribute in XML (android:gravity = “center”) we have the “setGravity” method. Easy to follow, isn't it? If we have worked a bit with the XML, this is almost trivial.
Let's see an example in XML and its dual in Java code.
<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:id="@+android:id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
We have a LinearLayout, and inside of it a TextView. It's that simple!
Now let's see how to create this structure in Java code
Inside an Activity
LinearLayout linear;
TextView text;
Inside the onCreate method (for example)
linear = new LinearLayout(this);
linear.setOrientation(LinearLayout.VERTICAL);
text = new TextView(this);
text.setText("This is an example for the Bright Hub!");
linear.addView(text);
setContentView(linear);
We create the LinearLayout as an object, with the “this” argument we are passing the “Context” of the Activity.
We then set the orientation of the LinearLayout with the “setOrientation” method.
Next, we create the “textView” element, the same way as we created the linear layout, we add some text to the TextView and finally we add the textView to the LinearLayout.
To show the Java created view on the screen we have to use the “setContentView” method from the Activity.
Take note that we have not defined the layout height and width. This is done using “LayoutParams”. But I will write about this in another article, because is a bit more complex.
So, here is a basic example. With time, we will create more and more complex examples.
Any questions or doubts? Just ask me!