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:
(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.
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
Inside the onCreate method (for example)
linear = new LinearLayout(this);
text = new TextView(this);
text.setText("This is an example for the Bright Hub!");
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!