Monday, November 28, 2011

Android Development 101- Part 2:Graphical Elements


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_content.  fill_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.xml all 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.xml and 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:

1import android.widget.Button;
2import 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:

1import android.view.View.OnClickListener;
2import android.widget.Toast;
3import android.content.Context;
4import 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.

1public class HelloMain extends Activity {
2EditText 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
03public void onCreate(Bundle savedInstanceState)
04{
05super.onCreate(savedInstanceState);
06setContentView(R.layout.main);
07// Capture our button from layout
08Button button = (Button)findViewById(R.id.go);
09// Register the onClick listener with the implementation above
10button.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
02private OnClickListener mAddListener = new OnClickListener()
03{
04public void onClick(View v)
05{
06long id = 0;
07// do something when the button is clicked
08try
09{
10helloName = (EditText)findViewById(R.id.helloName);

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.

1Context context = getApplicationContext();
2CharSequence text = "Hello " + helloName.getText() + "!";
3int duration = Toast.LENGTH_LONG;
4Toast toast = Toast.makeText(context, text, duration);
5toast.show();


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}
02catch (Exception ex)
03{
04Context context = getApplicationContext();
05CharSequence text = ex.toString() + "ID = " + id;
06int duration = Toast.LENGTH_LONG;
07Toast toast = Toast.makeText(context, text, duration);
08toast.show();
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.  Until next time, Happy Hacking!

No comments:

Post a Comment

thank you