quinta-feira, 11 de outubro de 2012

Layouts

Hello everyone.

Now that we know how to install Android on our machine, and how to create a simple application, we will learn to create layouts in Android. In Android, layouts are created using XML files with a very rigid structured and standard language, but also very simple and intuitive, due to the excellent structure created by Google.

There are several types of layout in Android: FrameLayout, LinearLayout, TableLayout, among others. In this post, we'll cover basically the 3 layouts cited in this paragraph.

FrameLayout
The FrameLayout is the most basic layout on Android. In this layout, we have only one layout structure stored. However, such structure may be another layout. This layout is often used in generic layouts, such as tabs and screens whose layout changes throughout it's execution. We will use this layout as a basis to teach many basic concepts of layout in Android.

For example, in Android there are various types of graphic components:


  • TextView → Displays text on the screen. It's definitely the most used graphic component in Android.
  • ImageView → Shows a picture or just a window on the screen. Every time you need to show a picture or a colored window, this component is used.
  • EditText → The above components only shows informations on the screen. But EditText gets a text typed by the user, which can be used to interact with the Android application.
  • Button → This component is one of the most common in any layout system. In this component, an action is performed after a click be given.
  • CheckBox → A component that basically has two values​​: true or false. Commonly used to represent the system settings.
  • RadioGroup → Quite useful component to show several options listed on the screen, where only one of them must be clicked. Widely used in multiple-choice questions.


And there are several parameters for each component in a graph layout in Android. To fully understand how those parameters, below is shown the use of some of these components in a FrameLayout. Below is shown the source code that creates the XML layout.



And the generated layout.



In the source code above, we have some parameters, which are explained below:


  • android:layout_width="match_parent" → In creation of layouts in Android, we always call a parameter using the prefix "android:". In this case, the last word of the parameter is "layout_width". This parameter defines the width size of the screen we are creating. This size can be a fixed size (in pixels, pixel density, or other formatting units) or expandable sizes. In this case, it hass a expandable size. There are 3 expandable sizes in Android:
    • fill_parent → With this option, the parameter size is maximum (ie, the current screen size). For example, if the mobile phone screen or tablet that we're dealing is 800 x 600 pixels, if we have in a FrameLayout the parameter android:layout_width="fill_parent", the width size of the screen we are creating will be 600 pixels. Starting from API 8 (Froyo, Android 2.2), this option was discontinued, and it's operation became the "match_parent" option.
    • wrap_content → With this option, the parameter size will be minimal, based on the child components of the current layout. For example, if we define the width of the current layout with layout_width parameter, as follows: android:layout_width="wrap_content", we are indicating that the width size of the screen is the size of the child component of this layout. In the case of the XML we are analyzing, it's child component is a TextView. If, for example, this TextView has a size of 20 x 20 (height x width) pixels, then the size of the layout is the same. That's what makes wrap_content. If we have fill_parent instead, the layout size wouldn't be 20 x 20 pixels, but 800 x 600 pixels (equivalent to the size of the mobile phone screen).
    • match_parent → Keeps the size inherited by the parent component. If there is no parent component, the size will be maximum (ie, the screen size). In XML we have a TextView and its parent component, which is a FrameLayout. If we put in the TextView parameter android:layout_width="match_parent", the width of the current screen will be the same width as the FrameLayout.
  • android:layout_height="match_parent" → This parameter defines the height of the screen that we are creating.
  • android:gravity="center_horizontal" → This parameter sets the alignment of the components of this layout. In this case, the alignment will be centered and horizontal.
  • android:text="Example" → This parameter defines the text of the current component.

Well, many concepts have been explained above. To understand them better, there is no other way than pick the options of each parameter and test. For example, here we have the same XML from above, but this time with the parameter android:gravity component from the changed TextView, from "center_horizontal" to "center_vertical".



And below we have the same XML as above, but this time with the parameter android:gravity from the TextView component, changed from "center_horizontal" to "center".



Let's continue modifying components options, because this way we will understand better the behavior of each parameter. Below there is the resulting layout when we modify the parameters android:layout_width and android:layout_height to "match_parent" to "wrap_content".



Thus, the size of the FrameLayout became the same size as the TextView. Hard to understand? So let's give the TextView a color:



The result is shown below.



Now it's easy to understand that the FrameLayout size of became the same size of the TextView. Now, if we change the parameters android:layout_width and android:layout_height of the FrameLayout from "wrap_content" to "match_parent" (which is the original value, displayed in the 1st picture of this topic), we have the following result.



So, in the previous example, the size of FrameLayout had become the same size of the TextView, through the use of "wrap_content". Now, the size of the FrameLayout became the size of the mobile phone screen, by using the "match_parent" option. Understanding these concepts of screen size expandable options is INDISPENSABLE to develop any layout in Android. It's extremely important to understand these concepts, otherwise the creation of layout's in Android will become much more complicated.

Continuing FrameLayout explanation, is shown below the XML from above with some more options in order to make the text appear more elegant.



The result of this new XML is shown below:



In this new XML, we changed the background color of the FrameLayout from black (default color) to blue, through the parameter android:background with the value "#2244AA", that is a soft blue. But why the majority of the screen is in white color? Because that's the color of the TextView (through option android:background="#FFFFFF"). As the size screen parameters from the FrameLayout and TextView are "match_parent", the screen size is the size of the TextView. However, we have a new parameter in FrameLayout: android:padding="5dp". What is this parameter? With this parameter, you create an inner margin between the FrameLayout and the TextView, with size of 5dp. The term "dp" can be understood here.

Thus, as the color of the FrameLayout is blue, and from the TextView is white, we have a contrast on the screen, giving the impression that a border was created.

Following the explanation, we have the options android:textsize (text size), android:textstyle (text style, which is bold in this case), and android:textColor (text color, which is red in this case).

Now we will talk about other types of layout.

LinearLayout
In FrameLayout we have only one child component. But in LinearLayout, we have several. This layout is designed for cases like several structures on the screen in a linear way. In this layout we have a parameter that don't exist in FrameLayout: android:orientation. It can have "vertical" or "horizontal" options. To demonstrate it's operation, we will use another XML, shown below.



Now we have more than one component on the screen. The result of the above XML is shown below.



So, we have 2 TextView's, one under the other, in vertical orientation. Since both TextView has the parameters android:layout_width="match_parent" and android:layout_height="wrap_content", we have the width with a maximum length and the height with minimum size (the size of the TextView). Below is the inversion of those values​​, where the orientation of the LinearLayout is horizontal.



Here is the result of this new XML:



As the TextView's were very close, we can give a spacing between them. This is shown in the following XML:



Here is the result:



What was added was now the parameter android:layout_margin="5dp". It created an outside edge (do not confuse with padding, which is an inset) between the 2 TextView's. But still, the texts are too "stuck" in TextView. So now, we will use the padding to give an internal spacing in their writing.



Here is the result:



To end this basic explanation about LinearLayout's, we will speak about the parameter layout_weight. Below we have a new XML.



In it, we have included a new TextView, and modified the orientation of the LinearLayout from horizontal to vertical. However, we included the parameter android:layout_weight="1". This parameter gives priority to the size of the TextView where it is set (in this case, the 1st TextView). In other words, it boosts the size of the width/height of this component, overwriting the effectiveness (making useful operation) of the parameter android:layout_width and android:layout_height. Thus, it "extends" the size of this TextView to where the screen size leave. The result can be seen below:



And now, the result when we set android:layout_weight="1" also in the 2nd TextView.



And also in 3rd.



So, the parameter layout_weight gives "weight" for each component. As in the previous image all components have same weight, they occupy the same place on the screen. However, this parameter overrides the functionality of parameters android:layout_width and android:layout_height. To finish layout_weight explanation, what happens when we set all TextView as android:layout_weight="1", but the 1st TextView as android:layout_weight="2"?



That is what happends. It balanced the weight of components according to the value of the parameters android:layout_weight of each TextView.

Now, we will learn a bit about TableLayout.

TableLayout
This layout is commonly used when we need listing various components in the same row, along a same screen. For example, create a layout with 18 TextView's split 3-3 along 6 lines. To create a layout like that, we could use 6 LinearLayout's, but it would spend much source code in XML, plus lots of memory on Android. The solution for this case would be using a TableLayout.

If we wanna have certain components used in only one line of TableLayout, the component used is TableRow. Below is an example of it's use:



And the result of this XML:



With the above example, we can deduce what effect one TableLayout has. If the component TableRow wouldn't be used, the TableLayout would become a LinearLayout.

To better understand the functioning of TableLayout, we will practice an exercise. We will create a layout with 6 lines, each containing 3 TextView's of equal size. The result will be the layout below.



Well, we can now realize that the generated XML source code will be huge (passing 250 lines for both cases), because we have to replicate enough code to create those 18's TextView. One tip to avoid this re-typing job is to create a style for our TextView. To create a style, we must create an XML file in the folder res/values​​, called styles.xml. In this file, we will create the generic layout of our TextView's. Below is shown how would be the syntax of this file.



Now we need to put this new style in our XML. So, we would have as result an XML file with only 110 lines, more than half the size of lines of XML without using styles.



-----

With these 3 types of layout we can create a tremendous amount of layout in Android. There are other types of layout (and other visual components) that will be seen on the blog in the next posts.

If someone has a question, suggestion or criticism, feel at ease.

domingo, 7 de outubro de 2012

Creating the first application on Android

Hello everyone.

Now that it has been explained how to install Eclipse and Android, we will begin to deal with the creation of applications on Android.

The creation of a application on Android can be divided into several steps.

Step 1 - Create the Android project on Eclipse
To create a application on Android, we first need to create a programming project for this application. The image below demonstrates this task:


Then, choose the option "Android Application Project", as shown below.


Then a new window will appear where you will type the project name. AndroidExample will be the name for this project. Notice that as we fill the project name, the text box "Package Name" is filled in with the name of the default package of the project.

NOTE: A package is a folder structure where the project files will be separated. This will be more detailed below.

Note also that the text box "Build SDK" has the value "Android 2.3.3 (API 10)", and the text box "Minimum SDK Required" has the value "API 8: Android 2.2 (Froyo)". This means that the minimum supported version for this application is the 2.2, and the recommended is the 2.3.3. Thus, this program WON'T RUN on devices with lower versions than the 2.2 (as version 1.5 - Cupcake, 1.6 - Donut, and 2.1 - Eclair).

The next screen in the creation of the project is shown below. Here, we have the layout option for the screens of the program we're creating. In this case, we will use the "BlankActivity".


Finally, we have the last screen before actually creating the design of our program in Android. On this screen, we'll choose the name of the file containing the graphic interface of the home screen of our program. In this case the name activity_main was chosen.


At the end of this process, our project will be created:


The contents of each folder of our project will be explained below, in the next step.

Step 2 - Understanding the structure of our project in Android
An application projetc for Android has a rigidly defined structure. It is divided into:

  • AndroidManifest.xml → This is the main file of our project.

    In this XML file we have the general settings of our program, as the version number of our program (android:versionCode="1") and the minimum and maximum supported SDK versions. In this case, the minimum version is the SDK 8, generally known as the the 2.2 version (called Froyo), and the maximum version is the SDK 10, generally known as the 2.3.3 version (called Gingerbread).

    We also have other information, such as the icon of our program (android:icon="@drawable/ic_launcher"), it's theme layout (android:theme="@style/AppTheme"), the name of the program (android:label="@string/app_name"), it's main screen (android:name=".MainActivity"), and other information that are not so important now.

  • src/ → In this folder we have all the source code in Java.

    When we create our project, only the file MainActivity.java  s created. This is the file that contains the home screen of our program. In Android, a screen is known as an Activity. So, if we want to create a screen, we have to extend the class from an Activity.

    A Activity has a "life cycle", which is best explained here, more specifically in the "Activity Lifecycle" section. In short, an Activity (which from now on we will call "screen") has events that are activated when the focus of the application goes for the first time to the screen (onCreate), when the focus goes to the application (onResume), when we minimize the application (onPause), and when we finish the application (onDestroy), among others.

    Each screen must MANDATORILY have a graphical user interface associated with it. This is done through the method setContentView(), which must be implemented in onCreate event. In our application, we set the layout of MainActivity with activity_main layout, which is set as an argument of the method setContentView(). So we have our screen and it's layout correctly done.

    Other things about MainActivity source code, like what is the event onCreateOptionsMenu and why the argument of the method setContentView() is R.layout.activity_main and not just activity_main) will be explained below.


  • res/ → In this folder we have other configuration files, such as strings, menus, colors, layout styles, and also all the media files (images, audio and video) of our program.

    Notice that in the figure below we have 4 folders whose prefix is drawable. It's in this folder we store images and animations of our project. But why are 4 folders and not just one?

    Unlike the iOS mobile operating system, which has only one type of mobile phone (iPhone) and one type of tablet (iPad), in Android we have hundreds of phones and tablets. So we'll have also a great multitude of screen possible sizes in which an Android application can run. Foreseeing this feature, Google chose to create 4 different screen sizes: ldpi, mdpi, hdpi and xhdpi.

    The acronym ldpi means "low density of pixels"; mdpi means "medium density of pixels"; hdpi means "high density of pixels"; and xhdpi means "extremely high density of pixels". In short, respectively, we can interpret these acronyms like "small screen size" (like Sony Ericsson Xperia Mini), "medium screen size" (Motorola Atrix), "large screen size" (Samsung Galaxy S 5) and "very large screen size" (usually tablets). Further details here.

    Following, we have the folder layout/ (where there are all the graphical interfaces to be used in our project), the folder menu/ (where there are all the menus of our project), and folder values/​ (where we can have different types of structures common to our project, such as strings, layout themes, arrays, colors, among others).

    The layout of each screen of Android will be better explained in another topic, as well as the menus. About strings, a common question is to understand why we need to declare all the strings in an XML file, and not in the actual source code in Java.

    This is another thoughtful practice of Google. How the Android mobile operating system is the most used in the world, being used in hundreds of different countries, it's necessary to have a support for internationalization. In other words, there must be a easy way to an application in a language be changed to another language. The solution found by Google was create the folder res/, a specific folder to store certain structures of our program. In this case, strings.

    So, suffice only modify the text in the file strings.xml to our application be supported in various languages​​. In short, it's much simpler to modify the contents of the file strings.xml than changing out, one by one, all Java files of our project.

  • R → This is the most important class of any program in Android. Here are stored all memory locations of the components used in our application (Java classes, XML files, images, sound files, audio, etc).

    These memory locations are basically integers. If, for example, we want to reference an image file as the file ic_launcher.png (the icon of our application), we simply need to call the memory location where this image is stored. Although this sounds somewhat complicated, it is simpler than it seems. We just need to call the image as follows: R.drawable.ic_launcher. In other words, R.<image folder>.<image name> (R dot <image folder> dot <image name>).

    Therefore, in the method setContentView() of class MainActivity.java, the argument that we have is R.layout.activity_main, not activity_main.

    NOTE: This class is self-generated. Even if we modify it manually, it'll be automatically generated again.

Now that we understand a little bit about the structure of our project, we need to run it to see how a program runs in Android, through Eclipse. This is explained in the following step.

Step 3 - Running our project
To run our project, first we need to create an emulator of Android. This is pretty simple to do. Just click the menu "Window" from the Eclipse menu bar, then "AVD Manager" (Android Virtual Devices Manager). Then, in the new opened window, simply click "New". Then, the window below will be opened.


Now simply choose the name of our emulator, it's "Target" (version of the Android SDK), it's screen size into the check button "Built-in", and then click "Create AVD". And it's done! We have an Android emulator ready to be used.

To run our program, simply right-click on the project name in the "Package Explorer" (or even within any files of our project), click on "Run As", and then in "Android Application". Thus, the emulator will be opened, and our application will run.

Below we can check the execution of our application.


And it's done! We've created our first Android application! It's a simple application that only shows a text on the screen.

-----

In the following topics will be shown more interesting applications.

If someone has a question, suggestion or criticism, feel at ease.

Starting programming in Android

Hello everyone.

Before anything, It's necessary to be explained step by step how we can create a development environment in Android. There is several posts in about it in Internet, but as sometimes some people asks me about it, I've decided to create this post.

The programming to Android devices may be performed through programming languages as Java and Scala, and using tools like NetBeans, Eclipse, or even through command line.

In this post will be showed the most common approach, that is using Java programming language and the Eclipse framework
NOTE: For Android programming, using Java and Eclipse framework, is demanded a minimum knowledge in computer programming. If you don't meet these requirements, this post isn't appropriate to you.

The installation steps of the Android in your machine may be divided in several steps.

Step 1 - Download the Java SDK
We can't forget that is mandatory to have the Java Development Kit (SDK). The download of this development package can be accomplished here.

Also, Java must be configured with it’s Enviroment Variables. If isn’t, follow this link.

For the download be done, it's necessary to accept the license agreement for the Java using. To accept, simply click on the button, as shown below.


This step is common to download this package for all operating systems, like Linux, Windows and Mac.

Step 2 - Download Eclipse Kepler
Now that we have the Java SDK installed on the computer, the next step is to download the Eclipse framework. This framework is an IDE (Integrated Development Environment), an integrated development environment for computer programs. Is in this environment that Android applications are created.

The download of this framework can be done here. This site automatically detects the operating system you are using, showing options for downloading this package. The package that we must download is shown below:


It must be downloaded the STANDARD version of Eclipse, and not others like EE Developers or C/C + + Developers.

This is the latest version of Eclipse, known as Eclipse Kepler. To download, just click the links beside the image above (in this case, for Windows). Then you will be redirected to a new site where the download will be performed.

Step 3 - Install Android on Eclipse
The next step is to install the Android on Eclipse. The Eclipse is a program that requires no installation. Its downloaded content already contains everything we need to initialize it's execution. It is advisable to leave this content in a folder like C:/eclipse (for Windows), or /home/<user>/eclipse (in the case of Linux or Mac).

To open the Eclipse, just click the purple icon called "eclipse". Before Eclipse is open, it will ask you to be informed the "workspace" where you will place the projects that will be developed. In my case, I chose the path C:/workspace (for Windows) and /home/<user>/workspace (in the case of Linux or Mac).


Then, Eclipse will open, and what we'll have on the screen will be this:


Now we need to install the Android on Eclipse. For this, we must click on Help option from the menu bar, and then click Install New Software. After that, you should click "Add..." and give the name and the link of what we'll download on Eclipse.

The name I always use is "Android SDK", and the link (to be placed in the "Location:") is: https://dl-ssl.google.com/android/eclipse/.

After that, we must confirm the next steps (all of them, even when it is required to restart Eclipse), and after 5 to 10 minutes, the new look of Eclipse will be this:


Now, there are a few new icons in Eclipse, including two icons that appear with the Android mascot, a sign that Android has been downloaded correctly on the machine.

Step 4 - Refresh the Android SDK Manager
Now that Android has already been installed, we need to update their packages to create applications for several existing versions of Android (1.5, 1.6, 2.1, 2.2, 2.3, 3.0, 3.1, 4.0, 4.1, 4.2, 4.3, and the latest 4.4).

To do so, just click on the icon that appears with the Android mascot above a white arrow. This icon will open the SDK Manager.


Now we just choose which versions of Android (API calls) we want to get to development. The wise choice is all. However, this step takes a long time. Get ready to wait for more than 1 hour.

With the SDK updated, it'll be available several examples (Samples) of Android source code, and also the special libraries of Google, such as Google Maps library.

-----

With these 4 steps, now we can start creating our first programs in Android. But that will be seen in an upcoming topic.

If someone has a question, suggestion or criticism, feel at ease.