Part–2 Graphical Elements

Posted: July 28, 2010 in Android, Development


In this tutorial, we will be continuing from where we left off with the “hello world” application.  This time adding a graphical user interface (GUI) and a “toast”. The GUI will consist of a button, textbox and a label. The “toast” will be issued onto the screen when the button is pressed.

Some may wonder what a toast is.  Well, for non-programmers, a toast is a text notification that for the most part is used only to display an error on the screen (I am a big fan of using toasts instead of an alert on the screen as its less intrusive).  For this article we will use a toast to display a message on the screen that will take the text in the textbox and issue a “Hello Greg” onto the bottom of the screen.  After this article completed you will be able to successfully make toast commands, design the layout of the hello world program, and pull text from a textbox.

We are going to start off by copy our existing Hello World project so that we can use the original in every way but have two separate projects to show the difference and both can be used as references.  To do this we will right click on the root of our HelloWorld project in the right hand pane (Navigation Explorer), navigate to copy (not Copy Qualified Name) and click it.  Then find a blank space in the Navigation Explorer, right click again and click paste.  You will be asked to supply a new name for this project and whether to use the default location.  We will name the new project ImprovedHelloWorld and we will leave the checkbox checked that says “use default location”.  Press OK and the new project will be generated from the old one.


The first thing we are going to accomplish is changing the strings.xml file to add another node under app_name.  We will do this by copying the node above it and pasting the copied material directly under the last </string> element.  Then we will change the name of the string to press and in between we will write Press Me!.  Next we will alter the hello node and change the text to say Enter Your Name Here: instead of Hello Android, Hello World!. This being accomplished we now need to design the GUI (Graphical User Interface).


To do this navigate to main.xml and we are going to go over what everything does up to this point.  We first off have a node called LinearLayout which essentially creates a space for adding objects such as textboxes, buttons and the like and will format the layout for us.  So LinearLayout will organize one thing right after the other in a one column and one row type of deal.  Next we have a TextView which in any other label we could call a label.  Now to go over what all of the parameters are in the nodes we just mentioned.  android:layout_width & android:layout_height are used to determine what will happen to an object when it is used within a layout.  There are two options when using this and they are fill_parent or wrap_contentfill_parent will do exactly as it states, it will size the object so that it will fill the screen either vertically or horizontally.  wrap_content will format the object to expand or shrink to the size of the content displayed within.  Both of these variables can be used in many different objects including but not limited to Layouts, Text Views, Text Boxes, and Buttons.  android:text is used in certain objects like TextViews and TextBoxes to display text to the user.  As of right now, we are presenting the user with text but calling it from strings.xml instead of entering the text right in the node itself.  To reference strings.xmlall that is needed is to put @string/press, where press is the name of your variable, inside the quotations.

Now that we are familiar with the terms, we will need to modify this to first house a label, textbox and finally a button.  To do this we will simply add a textbox and button since we already took care of the label in the string.xml.  To add a Textbox we will start on a new line under ending of the <TextView /> node.  Just to be clear I will add code inline and explain why we are adding it afterwards. <EditText android:id=”@+id/helloName” android:layout_width=”fill_parent” android:layout_height=”wrap_content” />.  EditText will be our textbox in this instance.  Also when giving items an ID it is best to follow these practises of adding@+id/ before your variable name which makes it possible to tie into your .java file later.  Next we will add <Button android:id=”@+id/go” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”@string/press” /> directly underneath the ending of our EditText node.  Notice we are referencing the string.xmland calling the node that says Press Me! which will appear on our button now.  If you were to run this project now you would be able to see the layout of the program we just made but we are unable to get it to do anything except enter text in the textbox.

This next section will contain a lot of code and I will provide most of the screenshots of the code to help you through.  First, it is good to realize every time you would like to reference an object in your layout we need to import it.  We will need to add imports for our button and textbox.  We can do that bu adding these lines of code to the imports section at the top:

1 import android.widget.Button;

2 import android.widget.EditText;

After that we will need to include four more imports, the first being for event listen to add to our button, the second will be for the toast that we will call when the event handler runs, the third being the context of the application and the fourth to get the view of the application and handle the layout and interaction.  These imports can be added under the previous ones and will look like this:

1 import android.view.View.OnClickListener;

2 import android.widget.Toast;

3 import android.content.Context;

4 import android.view.View;

After these are added to your imports we are ready to get into coding the event handler for our button and the onCreate functions, which is called when the program is started.  To make things easier and to complement the screenshot, I will post the rest of the code and explain what the important lines are doing and why we are using them.

1 public class HelloMain extends Activity {

2 EditText helloName;

We are creating a reference to our textbox above any function so that it only has to be declared once but instantiated many times if need be.

01 /** Called when the activity is first created. */

02 @Override

03 public void onCreate(Bundle savedInstanceState)

04 {

05 super.onCreate(savedInstanceState);

06 setContentView(R.layout.main);

07 // Capture our button from layout

08 Button button = (Button)findViewById(;

09 // Register the onClick listener with the implementation above

10 button.setOnClickListener(mAddListener);

11 }

Above we capture the button from the layout using a variable.  With this variable we are going to assign it an onClick Event Handler as shown on the last line above.  Below we are creating the Event Handler for it to be hooked in above.  After creating this function it will be able to pull the text from the TextBox and display it with static text.

01 // Create an anonymous implementation of OnClickListener

02 private OnClickListener mAddListener = new OnClickListener()

03 {

04 public void onClick(View v)

05 {

06 long id = 0;

07 // do something when the button is clicked

08 try

09 {

10 helloName = (EditText)findViewById(;

Here we instantiate the TextBox we declared earlier and capture the Textbox in the layout by finding it by the ID that we gave it.

1 Context context = getApplicationContext();

2 CharSequence text = "Hello " + helloName.getText() + "!";

3 int duration = Toast.LENGTH_LONG;

4 Toast toast = Toast.makeText(context, text, duration);


The above code will take Context (the facet to our applications enviroment) and and add it to our Toast along with our dynamic CharSequence text and the length the Toast will appear onscreen, which in this case we want it to be longer.  It is key to note how to make a Toast as it is more efficient that popping up textboxes to the user as well as it is less distracting.

01 }

02 catch (Exception ex)

03 {

04 Context context = getApplicationContext();

05 CharSequence text = ex.toString() + "ID = " + id;

06 int duration = Toast.LENGTH_LONG;

07 Toast toast = Toast.makeText(context, text, duration);


09 }

10 }

11 };

12 }

The last thing we are doing for this function is putting all the important stuff mentioned above into a try catch statement which will try our important code and if there is an error it will display a Toast letting us know there was an error and a message about that error.  For functions such as these is it crucial to have precautions in place to catch errors and not have a program force close.  It is important to put the user first in thinking about UI and any error messages that might occur.  If an error somehow sneaks into your program try catch statements will catch the error and make it “cute and fuzzy” for the user.

Top half of code:


Bottom half of code, elapsed by previous view of code:


After we have coded the main content for our .java file, we can now proceed to run the application and view our completed Improved Hello World program.  Notice that when you press the button and your textbox has not text in it that the program will still function correctly.  This is a good feature to have so that you don’t start seeing Toasts containing error messages.  The completed product should look like this when the button is pressed:


This would conclude our Improved Hello World example but the learning is far from over.  Next post we will examine Databases and a look into some simple queries as well as building a database from the ground up.  As always, if you have any problems with coding this article, feel free to leave a comment and I will assist in any way possible! If you can’t wait for the next post you can read up on databases before the next posting.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s