Android UI Java Programming Tutorial

Written by:  • Edited by: Simon Hill
Updated Jun 24, 2011
• Related Guides: Android | XML | Java

Learn how to create simple UI elements using Java code instead of XML in this easy-to-follow tutorial.

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!

Java Objects

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!

References

Author's own experience.


Comments

Showing all 26 comments
 
Nizeshshakya Dec 21, 2011 2:59 AM
RE: Android UI Java Programming Tutorial
suppose I have :<br>&lt;edittext&lt;br&gt;        android:id="@+id/entry"<br>        android:layout_width="fill_parent"<br>        android:layout_height="wrap_content"<br>        android:background="@android/editbox_background"        android:layout_below=" id/textview"/&gt;in your code the how would I change that into a java code??&lt;/edittext&lt;br&gt;
Kenneth Vallejos Sep 12, 2011 10:37 AM
A good jump start
This small and concise tutorial of yours, Jbeerdev, was a huge time saver for me.

I was doing an app and I need to create a separate class that will take care of dynamic creation of my views. And here it was your tutorial helped me a lot.

Thanks again and more power to your career.
Anonymous Sep 3, 2011 6:22 AM
Dynamic button
I need to add the button dynamically.tell me the solution what to do.
Nagasaidulu Jul 21, 2011 5:39 AM
how can we get two textviews through above code
hello!
it's fine to create one text view and edit text but i cant create more
than one.
please help me.
Minas Jun 21, 2011 11:07 AM
Thank you
Thank you very much! I was looking for a way to do this!
Jbeerdev Jun 19, 2011 11:55 AM
RE: Android UI Java Programming Tutorial
I always recommend using XML for the view. This way you will have an application with the logic-view separate. If something in the view have to be changed, it will be more easy to change if you use XML.
Anonymous Jun 16, 2011 10:18 AM
Which is faster?
which of the two methods is better?
I'm more comfortable using java. Please suggest

Thanks
Purav Mar 12, 2011 6:23 AM
RE: How to create Android UI in Java Code: Layouts and Views Read more: http://www.brighthub.com/mobile/google-android/articles/48845/comments.aspx?cp=2#ixzz1GNpyEHac
Hi Jbeerdev,
Can you please explain how to align different views/widgets relative on one another in RelativeLayout, using java, and not XML.
for Ex: if i want to keep a Button the left of an EditText, then in XML, i write
<RelativeLayout...
<EditText android:id="@+id/text" />
<Button ....
android:layout_toRightOf="@id/text"
/>
</RelativeLayout>

now how do i do the same thing in java?
Aijaz Ali Dec 4, 2010 10:46 PM
How to take the image from the camera preview in android emulator?
As I have connected the usb camera with android emulator, now I want to capture that image from that preview.
if any one has idea then please send me the code for this.
Rizwan Nov 13, 2010 11:29 PM
string.xml file value overright
Hi, sorry for the long question, shortly here is what i want:

How can i over write one particular String from Strings.xml file from my java code, so that my program reads that specific String value from my java code and not from the Strings.xml file while the rest of Strings to be used as it is.
Jbeerdev Oct 25, 2010 10:34 AM
RE: Android UI Java Programming Tutorial
Hi.

About getting the layout in the xml and add a button (for example) in java code, it will be something like:

LinearLayout ln = (LinearLayout)findViewById(R.id.myLinearLayotId);

Button btn = new Button()

ln.add(btn);


This is pseudocode, but just you to get the idea.
Anonymous Oct 24, 2010 2:13 PM
get the layout from xml
Hello,
I made a layout in my xml code, and i want to add a button on that layout, but i want to do it in the java code. can you explain me how can i get the layout from the xml code ?
I hope you understood me.
thank you
Pushkar maid Sep 16, 2010 1:50 AM
android application
hi i need an android application who's source code i can view since i need to develop same application on win 7 mobile. can you suggest me any application which uses any features of mobile (eg: bluetooth). thank you
rosebeat Sep 8, 2010 1:49 AM
Need help with MySQL Connectivity
Hello Jbeer,
I am new to Android and i want to establish a connectivity with localhost database in MySQL. I know we need a little bit of PHP as an intermediate language and when android sends the request to PHP code, the PHP code execute the query and fetch data from localhost MySQL database. I have seen the tut online but they are very complicated. I need a simple code so that I can learn. Can you please help me here? I am new to java as well although I understand the basics.
Thanks in advance
Asma-ull-Hosna Aug 21, 2010 10:39 PM
Set object vertically
Hi,
How can I set the video screen/object vertically inside the screen.
Jbeerdev Aug 4, 2010 5:06 AM
RE: Android UI Java Programming Tutorial
Hi!

Daniel - I know that you can do it by code. I mean, creating a class that extends Button, for example, and use that class in xml. In the other way, I have not check it.

Alan Hale - Try using "LayoutParams" or "MarginLayoutParams", but I think that thoose are for height, width and margins. Anyway, to create complex relativelayouts, I suggest using xml. If is not possible, we can have a look at it and check the way to do what you want.
Daniel Aug 4, 2010 4:40 AM
Using XML created variables/objects in java code
Hi,

I was wondering if I can make layouts and views in XML as a placeholder and then use them to create instances that implement those classes? Some think like this:

View v1 = new DrawableView(getBaseContext());
findViewById(R.id.View01) = v1;

i know this code does not work, but just to get an idea what i wanna do.

thanks!
Alan Hale Jul 18, 2010 3:52 PM
android:layout_below in Java code?
Is it possible to set android:layout_below in Java, to position one view beneath another?
shailendra Jul 16, 2010 7:50 AM
thnx
real helpful 4 a biginner like me
Naresh Kaushik Jun 26, 2010 2:35 AM
How to handle key event on your own view
Hi dear

i want to draw a line by pressing down key in down direction,up key in up direction and so on. for that i have a class named MyView extending View. in which i want to draw line in onDraw() and handling it by using onKeyDown(). is it possible if yes plz tell me or if there is any other way to handle it then plz tell me that or provide me code for that
Jbeerdev Jun 22, 2010 7:15 AM
RE: Android UI Java Programming Tutorial
Hi Chiranjib Banerjee

I strongly recommend you to use RelativeLayouts in Xml. It's much cleaner and easy to mantain.

If you want, I can provide you some examples of RelativeLayouts with ImageViews in Xml.
Chiranjib Banerjee Jun 22, 2010 7:08 AM
Kindly provide me the Relative Layout code
Hi Simon,

Kindly provide me with the Java code for Relative Layout where I have ImageView component.
How can I position multiple ImageView in the same Relative Layout? Also , inform me how to get the click event for every ImageView.

Actually I have implemented in the Relative Layout in Java code but due to positioning issue (I have used setPadding() method for positioning ImageView on the Relative Layout) , I am getting the wrong value for clickevents of multiple ImageView

Kindly help
Jbeerdev Jun 9, 2010 3:45 AM
RE: Android UI Java Programming Tutorial
That's it. In the code I have written I have just focused in the more interesting pieces. If you are working with Eclipse, you will get compilance errors, just import the packages you need.
Anonymous Jun 9, 2010 3:40 AM
fix compile errors
You should include the packages.

import android.widget.LinearLayout;
import android.widget.TextView;
Anonymous May 22, 2010 9:37 PM
Android UI in Java Code
The example didn't compile. The complaint
was: cannot find symbol, class LinearLayout
cyberphreax May 20, 2010 4:13 PM
More elaborate example
I love your coding tutorials for android. Have you done any more tutorials on creating UI through code? I'd really like to change the height/width and padding of a textview from a configuration activity screen and have it change a home screen widget layout.
 
blog comments powered by Disqus
Email to a friend