Difference between revisions of "Creating an Example Android App in Android Studio"

From Techotopia
Jump to: navigation, search
(Defining the Project and SDK Settings)
(Understanding the Support Mode Settings)
Line 66: Line 66:
  
  
[[Image:android_studio_new_project_ready.png|The Android Studio new project wizard ready for next screen]]
+
[[Image:android_studio_new_project_ready2.png|The Android Studio new project wizard ready for next screen]]
 
   
 
   
 
Figure 1-3
 
Figure 1-3

Revision as of 14:33, 10 April 2014



The preceding chapters of this book have covered the steps necessary to configure an environment suitable for the development of Android applications using the Android Studio IDE. Before moving on to slightly more advanced topics, now is a good time to validate that all of the required development packages are installed and functioning correctly. The best way to achieve this goal is to create an Android application and compile and run it. This chapter will cover the creation of a simple Android application project using Android Studio. Once the project has been created, a later chapter will explore the use of the Android emulator environment to perform a test run of the application.


Contents


Creating a New Android Project

The first step in the application development process is to create a new project within the Android Studio environment. Begin, therefore, by launching Android Studio so that the “Welcome to Android Studio” screen appears as illustrated in Figure 1-1:


The Android Studio Welcome Screen

Figure 1-1


Once this window appears, Android Studio is ready for a new project to be created. To create the new project, simply click on the New Project… option to display the first screen of the New Project wizard as shown in Figure 1-2:

Creating a new project in Android Studio

Figure 1-2


Defining the Project and SDK Settings

In the New Project window, set both the Application name and Module name fields to AndroidSample. The application name is the name by which the application will be referenced and identified within Android Studio and is also the name that will be used when the completed application goes on sale in the Google Play store. The module name, on the other hand, is used to identify this as a self-contained unit of functionality within the project that is able to be compiled, run, debugged and tested within the Android Studio environment. More complex Android Studio projects can be made up of multiple modules, though for the purposes of this example, only one module will be created.

The Package Name is used to uniquely identify the application within the Android application ecosystem. It should be based on the reversed URL of your domain name followed by the name of the application. For example, if your domain is www.mycompany.com, and the application has been named AndroidSample, then the package name might be specified as follows:

com.mycompany.androidsample

If you do not have a domain name, you may also use example.com for the purposes of testing, though this will need to be changed before an application can be published:

com.example.androidsample

The module is then appended to the package name. For example:

com.mycompany.androidsample.mymodule

The Project location setting will default to a location in the folder named AndroidStudioProjects located in your home directory and may be changed by clicking on the button to the right of the text field containing the current path setting.

The next step is to specify some SDK settings. For the purposes of this example, the Minimum Required SDK should be set to API 8: Android 2.2 Froyo whilst the Target SDK and Compile with menus should all be set to the most recent version of the Android SDK. At the time of writing this is API 19: Android 4.4 (Kit Kat).

Make sure that the Create Activity and Create customer launcher icon options are selected. The former setting will ensure that the project is preconfigured with a template activity that will make the task of creating an example application easier. An activity is a single task that can be performed by the user within the context of an application and is typically analogous to a single user interface screen within an application. In asking for Android Studio to create an activity for us, therefore, the project will be primed with both a window onto which a user interface may be displayed and the code to ensure that the window appears when the application runs.

The custom launcher selection, on the other hand, will provide the option to specify the icon that will represent the application on the device screen.

Since this example takes the form of a fully functional application, make sure that the Mark this project as a library option is off.


Understanding the Support Mode Settings

The last set of options within the New Project screen relate to Support Modes. Android is a continually evolving platform with new versions being released on a regular basis. Each new version of Android introduces new features, support for which are included with the corresponding Android SDK release.

In a perfect world, all existing Android based devices would be upgraded to the latest Android version as soon as it is released. In practice, however, the majority of devices in use will continue to run older versions of Android. In order to build an application that will run on the widest possible number of device types, it is recommended that applications be configured to target a minimum SDK of API 8: Android 2.2 where possible.

In order to make some features of newer Android releases backwards compatible with older Android versions, Google provides developers with a set of support libraries. The Support Modes section of the New Project screen allows these support libraries to be added to the new project so that the corresponding features can be included in the application without limiting the application to devices running newer Android versions.

It is important to be aware, however, that support libraries are only available for a select group of new features for the simple reason that some new functionality is too deeply embedded into the latest Android release to be made backwards compatible. Printing content from an Android device, for example, is a feature introduced in Android 4.4 (API 19) for which no backward compatibility support library exists.

None of the support modes will be required for this example project, so leave the support mode options deselected.

Once these settings have been configured, the dialog should match that shown in Figure 1-3:


The Android Studio new project wizard ready for next screen

Figure 1-3


With the initial group of project settings correctly configured, click on the Next button to proceed with the configuration steps.

Configuring the Launcher Icon

Before the application can be submitted to the Google Play app store for sale it will need to have an icon associated with it. This icon is displayed on the screen of the Android device and is touched by the user to launch the application. The launch icon can take the form of a set of PNG image files, clipart or even text. Options are also provided on this screen to configure the background color of the launcher and to change the shape surrounding the icon.

When assigning image files for the launcher icon, images for a variety of screen resolutions and densities may be specified. If only a single image size is provided, the Android system will scale the image for different screens, potentially leading to some image quality degradation. For the purposes of this example, however, it is adequate to use the default icon images:


Configuring the launcher icon for a new project in Android Studio

Figure 1-4


Click Next to proceed with the configuration process.

Creating an Activity

The next step is to define the type of initial activity that is to be created for the application. A range of different activity types is available when developing Android applications. The Master/Detail Flow option will be covered in a later chapter. For the purposes of this example, however, simply select the option to create a Blank Activity before clicking Next.


Selecting an Activity type in Android Studio

Figure 1-5


With the Blank Activity option selected, click Next. On the final screen (Figure 1-6) name the activity AndroidSampleActivity. The activity will consist of a single user interface screen layout which, for the purposes of this example, should be named activity_android_sample. Finally, since this is a very simple, single screen activity, there is no need to specify a fragment layout name or select any extra features, so leave the Additional Features menu set to None as shown in Figure 1-6:


Configuring a new activity in Android Studio

Figure 1-6


Finally, click on Finish to initiate the project creation process.

Modifying the Example Application

At this point, Android Studio has created a minimal example application project and opened the main project.

The newly created project and references to associated files are listed in the Project view panel located on the left hand side of the main project window. This essentially mirrors the directory hierarchy and files located in the project folder on the local file system of the development computer. Within this hierarchy the AndroidSampleActivity class will be selected and the corresponding source code contained within the AndroidSampleActivity.java file displayed in the code editor:


The Android Studio main window

Figure 1-7


The example project created for us when we selected the option to create an activity consists of a user interface containing a label that will read “Hello World” when the application is executed.

The next step in this tutorial is to modify the user interface of our application so that it displays a larger text view object with a different message to the one provided for us by Android Studio. The user interface design for our activity is stored in a file named activity_android_sample.xml which, in turn, is located under AndroidSample -> src -> res -> layout in the project file hierarchy. Using the Project panel, locate this file as illustrated in Figure 1-8:


The Android Studio Project tool window

Figure 1-8


Once located, double click on the file to load it into the User Interface Designer tool which will appear in the center panel of the Android Studio main window:


The Android Studio Designer window

Figure 1-9


In the toolbar across the top of the layout editor panel is a menu that is currently set to Nexus 4 which is reflected in the visual representation of the device within the Designer panel. A wide range of other device options are available for selection by clicking on this menu.

To change the orientation of the device representation between landscape and portrait simply use the drop down menu immediately to the right of the device selection menu showing the Android studio designer orientation.png icon.

As can be seen in the device screen, the layout already includes a label that displays a Hello World! message. Running down the left hand side of the panel is a palette containing different categories of user interface components that may be used to construct a user interface, such as buttons, labels and text fields. It should be noted, however, that not all user interface components are obviously visible to the user. One such category consists of layouts. Android supports a variety of different layouts that provide different levels of control over how visual user interface components are positioned and managed on the screen. Though it is difficult to tell from looking at the visual representation of the user interface, the current design has been created using a RelativeLayout. This can be confirmed by reviewing the information in the Component Tree panel which, by default, is located in the upper right hand corner of the Designer panel and is shown in Figure 1-10:


The Android Studio Designer Component Tree

Figure 1-10


As we can see from the component tree hierarchy, the user interface consists of a RelativeLayout parent with a single child in the form of a TextView object.

The first step in modifying the application is to delete the TextView component from the design. Begin by clicking on the TextView object within the user interface view so that it appears with a blue border around it. Once selected, press the Delete key on the keyboard to remove the object from the layout.

In the Palette panel, locate the Widgets category. Click and drag the Large Text object and drop it in the center of the user interface design when the green marker lines appear to indicate the center of the display:


A TextView object centered in the parent layout

Figure 1-11


The Android Studio Designer tool also provides an alternative to dragging and dropping components from the palette on to the design layout. Components may also be added by selecting the required object from the palette and then simply clicking on the layout at the location where the component is to be placed.

The next step is to change the text that is currently displayed by the TextView component. Double click on the object in the design layout to display the text and id editing panel as illustrated in Figure 1-12. Within the panel, change the text property from “Large Text” to “Welcome to Android Studio”.


Android Studio UI Designer edit text and id

Figure 1-12


At this point it is important to explain the light bulb next to the TextView object in the layout. This indicates a possible problem and provides some recommended solutions. Clicking on the icon in this instance informs us that the problem is as follows:

[I18N] Hardcoded string “Welcome to Android Studio”, should use @string resource

This I18N message is informing us that a potential issue exists with regard to the future internationalization of the project (“I18N” comes from the fact that the word “internationalization” begins with an “I”, ends with an “N” and has 18 letters in between). The warning is reminding us that when developing Android applications, attributes and values such as text strings should be stored in the form of resources wherever possible. Doing so enables changes to the appearance of the application to be made by modifying resource files instead of changing the application source code. This can be especially valuable when translating a user interface to a different spoken language. If all of the text in a user interface is contained in a single resource file, for example, that file can be given to a translator who will then perform the translation work and return the translated file for inclusion in the application. This enables multiple languages to be targeted without the necessity for any source code changes to be made. In this instance, we are going to create a new resource named welcomestring and assign to it the string “Welcome to Android Studio”.

Click on the arrow to the right of the warning message to display the menu of possible solutions (Figure 1-13).


Extracting a string resource from a layout file in Android Studio

Figure 1-13


From the menu, select the Extract string resource option to display the Extract Resource dialog. In this dialog, enter welcomestring into the Resource name: field before clicking on OK. The string is now stored as a resource in the src -> res -> values -> strings.xml file.

Reviewing the Layout and Resource Files

Before moving on to the next chapter, we are going to look at some of the internal aspects of user interface design and resource handling. In the previous section, we made some changes to the user interface by modifying the activity_android_sample.xml file using the UI Designer tool. In fact, all that the Designer was doing was providing a user-friendly way to edit the underlying XML content of the file. In practice, there is no reason why you cannot modify the XML directly in order to make user interface changes and, in some instances, this may actually be quicker than using the Designer tool. At the bottom of the Designer panel are two tabs labeled Design and Text respectively. To switch to the XML view simply select the Text tab as shown in Figure 1-14:


Android Studio editing UI XML with Preview

Figure 1-14


As can be seen from the structure of the XML file, the user interface consists of the RelativeLayout component, which in turn, is the parent of the TextView object. We can also see that the text property of the TextView is set to our welcomestring resource. Although varying in complexity and content, all user interface layouts are structured in this hierarchical, XML based way.

One of the more powerful features of Android Studio can be found to the right hand side of the XML editing panel. This is the Preview panel and shows the current visual state of the layout. As changes are made to the XML layout, these will be reflected in the preview panel. To see this in action, modify the XML layout to change the background color of the RelativeLayout to a shade of red as follows:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.ebookfrenzy.androidsample.AndroidSampleActivity"
    android:background="#ff2438">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/welcomestring"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Note that the color of the preview changes in real-time to match the new setting in the XML file. Note also that a small red square appears in the left hand margin (also referred to as the gutter) of the XML editor next to the line containing the color setting. This is a visual cue to the fact that the color red has been set on a property. Change the color value to #a0ff28 and note that both the small square in the margin and the preview change to green.

Finally, use the Project view to locate the src -> res -> values -> strings.xml file and double click on it to load it into the editor. Currently the XML should read as follows:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">AndroidSample</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="welcomestring">Welcome to Android Studio</string>

</resources> 

As a demonstration of resources in action, change the string value currently assigned to the welcomestring resource and then return to the Designer by selecting the tab for the layout file in the editor panel. Note that the layout has picked up the new resource value for the welcome string.

There is also a quick way to access the value of a resource referenced in an XML file. With the Designer tool in Text mode, click on the “@string/welcomestring” property setting so that it highlights and then press Ctrl+B on the keyboard. Android Studio will subsequently open the strings.xml file and take you to the line in that file where this resource is declared. Use this opportunity to revert the string resource back to the original “Welcome to Android Studio” text.

Previewing the Layout

So far in this chapter, the layout has only been previewed on a representation of the Nexus 4 device. As previously discussed, the layout can be tested for other devices by making selections from the device menu in the toolbar across the top edge of the Designer panel. Another useful option provided by this menu is Preview All Screen Sizes which, when selected, shows the layout in all currently configured device configurations as demonstrated in Figure 1-15:


Android Studio Preview All Devices

Figure 1-15


To revert to a single preview layout, select the device menu once again, this time choosing the Remove Previews option.

Summary

Whilst not excessively complex, a number of steps are involved in setting up an Android development environment. Having performed those steps, it is worth working through a simple example to make sure the environment is correctly installed and configured. In this chapter, we have created a simple application and then used the Android Studio UI Designer to modify the user interface layout. In doing so, we explored the importance of using resources wherever possible, particularly in the case of string values, and briefly touched on the topic of layouts. Finally, we looked at the underlying XML that is used to store the user interface designs of Android applications.

Whilst it is useful to be able to preview a layout from within the Android Studio Designer tool, there is no substitute for testing an application by compiling and running it. In a later chapter entitled Creating an Android Virtual Device (AVD) in Android Studio, the steps necessary to set up an emulator for testing purposes will be covered in detail. Before running the application, however, the next chapter will take a small detour to provide a guided tour of the Android Studio user interface.