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

From Techotopia
Jump to: navigation, search
m (Text replacement - "<google>BUY_ANDROID_STUDIO</google>" to "<htmlet>androidstudio_a6</htmlet>")
m (Text replacement - "<table border="0" cellspacing="0">" to "<table border="0" cellspacing="0" width="100%">")
 
(7 intermediate revisions by the same user not shown)
Line 8: Line 8:
  
  
<htmlet>androidstudio_a6</htmlet>
+
<htmlet>androidstudio</htmlet>
  
  
Line 62: Line 62:
 
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.
 
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.
  
<google>ADSDAQBOX_FLOW</google>
+
<htmlet>adsdaqbox_flow</htmlet>
 
[[Image:android_studio_new_project_activity2.png|Selecting an Activity type in Android Studio]]
 
[[Image:android_studio_new_project_activity2.png|Selecting an Activity type in Android Studio]]
 
   
 
   
Line 92: Line 92:
 
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 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.
  
<htmlet>androidstudio_a6</htmlet>
+
<htmlet>androidstudio</htmlet>
  
 
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 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.
Line 241: Line 241:
  
  
<htmlet>androidstudio_a6</htmlet>
+
<htmlet>androidstudio</htmlet>
  
  
 +
 +
<htmlet>ezoicbottom</htmlet>
 
<hr>
 
<hr>
 
<table border="0" cellspacing="0" width="100%">
 
<table border="0" cellspacing="0" width="100%">

Latest revision as of 20:01, 27 October 2016

PreviousTable of ContentsNext
Setting up a Windows, Linux or Mac OS X Android Studio Development EnvironmentA Tour of the Android Studio User Interface


You are currently reading the Android Studio 1.x - Android 5 Edition of this book.

Purchase the fully updated Android Studio Hedgehog Edition of this publication in eBook ($32.99) or Print ($49.99) format

Android Studio Hedgehog Essentials - Java Edition Print and eBook (PDF) editions contain 87 chapters and over 800 pages
Buy Print Preview Book


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 3-1:


The Android Studio Welcome Screen

Figure 3-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 Start a new Android Studio project option to display the first screen of the New Project wizard as shown in Figure 3-2:


Creating a new project in Android Studio

Figure 3-2

Defining the Project and SDK Settings

In the New Project window, set the Application name field 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 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 ebookfrenzy.com for the purposes of testing, though this will need to be changed before an application can be published:

com.ebookfrenzy.androidsample

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.

Click Next to proceed. On the form factors screen, enable the Phone and Tablet option and set the minimum SDK setting to API 8: Android 2.2 (Froyo). The reason for selecting an older SDK release is that this ensures that the finished application will be able to run on the widest possible range of Android devices. The higher the minimum SDK selection, the more the application will be restricted to newer Android devices. A useful chart (Figure 3 3) can be viewed by clicking on the Help me choose link. This outlines the various SDK versions and API levels available for use and the percentage of Android devices in the marketplace on which the application will run if that SDK is used as the minimum level. In general it should only be necessary to select a more recent SDK when that release contains a specific feature that is required for your application. To help in the decision process, selecting an API level from the chart will display the features that are supported at that level.


The Android Studio API level chart

Figure 3-3


Since the project is not intended for Google TV, Google Glass or wearable devices, leave the remaining options disabled before clicking Next.


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.

Selecting an Activity type in Android Studio

Figure 3-4


With the Blank Activity option selected, click Next. On the final screen (Figure 3-5) name the activity and title 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 as shown in Figure 3-5 and with a menu resource named menu_android_sample:


Configuring a new activity in Android Studio

Figure 3-5


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 tool window located on the left hand side of the main project window. The Project tool window has a number of modes in which information can be displayed. By default, this panel will be in Android mode. This setting is controlled by the drop down menu at the top of the panel as highlighted in Figure 3-6. If the panel is not currently in Android mode, click on this menu and switch to Android mode:


Android studio changing project tool window mode.png

Figure 3-6


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.

You are currently reading the Android Studio 1.x - Android 5 Edition of this book.

Purchase the fully updated Android Studio Hedgehog Edition of this publication in eBook ($32.99) or Print ($49.99) format

Android Studio Hedgehog Essentials - Java Edition Print and eBook (PDF) editions contain 87 chapters and over 800 pages
Buy Print Preview Book

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 app -> res -> layout in the project file hierarchy. Using the Project panel, locate this file as illustrated in Figure 3-7:


The Android Studio Project tool window

Figure 3-7


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 3-8


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 3-9:


The Android Studio Designer Component Tree

Figure 3-9


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 3-10


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 3-11. Within the panel, change the text property from “Large Text” to “Welcome to Android Studio”.


Android Studio UI Designer edit text and id

Figure 3-11


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 3-12).


Extracting a string resource from a layout file in Android Studio

Figure 3-12


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 app -> 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 3-13:


Android Studio editing UI XML with Preview

Figure 3-13


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=".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 app -> 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 3-14:


Android Studio Preview All Devices

Figure 3-14


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.


You are currently reading the Android Studio 1.x - Android 5 Edition of this book.

Purchase the fully updated Android Studio Hedgehog Edition of this publication in eBook ($32.99) or Print ($49.99) format

Android Studio Hedgehog Essentials - Java Edition Print and eBook (PDF) editions contain 87 chapters and over 800 pages
Buy Print Preview Book



PreviousTable of ContentsNext
Setting up a Windows, Linux or Mac OS X Android Studio Development EnvironmentA Tour of the Android Studio User Interface