I have been writing a lot about the Android user interfaces, layouts and views… but every time I write about them, it has been to talk about “how to create a UI in XML code”… But what about Java code? I have said many times that its possible to write a layout hierarchy in Java code.
Before we actually learn to use this Java code let’s talk about creating a UI in Java code.
First, I would like to share my point of view and experience with the “Java-XML” and ways to create a UI:
Android gives us the chance to use XML to create our user interfaces, in my opinion, this is a great option! You can have in separate files, the logic of the application and the “view." In some places you may have to create the UI using Java code, because there is no another way. My advice is to use XML when you can. It will be easier.
Let’s create a simple layout-views interface using Java code!
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!
Author’s own experience.
This post is part of the series: How-to develop Google Android Applications - Going further
Here more functionality and simple how-to guides to show you how to work with Google Android