The Full Series of Android App Developemnt

Welcome to the second part of “The Beginner’s Guide to Android Development“. In this tutorial, we will continue to learn some basic android development techniques, such as adding button to our app using XML. If you haven’t already, be sure to read the part 1 of this series first!

The source code we are going to use in today lesson is what we have working on the previous published post called “Android Beginner: Creating Splash Screen“. Let’s open up the source code in Eclipse editor and start our tutorial!

Introduction to Android XML Layout

In Android system, developer use XML layout to defines and organizes the visual structure for user interface for activity or app widget. If you want to know more about Android XML layout, please read our previous article named “Android Linear Layout For Absolute Beginner”

Step 1: Create Button Under XML Root Element

Let’s open up the “main.xml” file. Do this by choosing /res/layout/ folder, double click on the main.xml file. This main.xml file is auto generated by Eclipse editor when we creating Android project, this XML layout has a visual container(Linear Layout) that contains a text view which displaying “Hello World, MainActivity!” on our app’s main screen.

Now, we would like to add in extra UI – Button into our app’s main screen. Following illustrate how our XML codes looks like:

As you can see above, we added <Button> into the main.xml file. The button element contains an id named “sound_efx”, its width and height, text size*(dimension), text style and text string named “btn_sound_efx”.

*Dimension

The dimension that we used for the text size is dp. Density-independent Pixels – An abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi (dots per inch) screen, on which 1dp is roughly equal to 1px. When running on a higher density screen, the number of pixels used to draw 1dp is scaled up by a factor appropriate for the screen’s dpi. Likewise, when on a lower density screen, the number of pixels used for 1dp is scaled down. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Using dp units (instead of px units) is a simple solution to making the view dimensions in your layout resize properly for different screen densities. In other words, it provides consistency for the real-world sizes of your UI elements across different devices.

Please bear in mind that it is a good practice to separate your XML layout with string resources file. This allows you to update every occurrence of the word “btn_sound_efx” in all layouts at the same time by just editing your string resources file.

Step 2: Edit String values Using String Resources

To edit the text of the button, let’s open up the string resources file – “strings.xml” which stored under /res/values/. Then add a new row of string element inside the strings.xml file: