Table of Contents
The Story behind the Succinctly Series of Books
About the Author
Chapter 1 Setting Up
Chapter 2 Hello, Android
Chapter 3 The Activity Lifecycle
Chapter 4 User Interface Layouts
Chapter 5 User Interface Widgets
Chapter 6 Fragments
Chapter 7 Application Data
Detailed Table of Contents
Introduction
Android is an open source operating system built on top of Linux. It powers a plethora of devices, from smart phones to tablets to gaming consoles (along with a vast array of other consumer electronics). According to the International Data Corporation, Android had over 70 percent market share for worldwide smartphones in the last quarter of 2012, so developing for this platform has the potential to reach a very large number of mobile users.
Figure 1: The Android Logo
Android is the main alternative to the iOS platform for mobile applications, but unlike iOS, Android projects can easily be created using OS X, Windows, or Linux-based computers. And since Android uses the Java programming language, developers coming from a C# background will most likely feel more comfortable than they would with iOS’s Objective-C programming language.
The goal of Android Programming Succinctly is to guide you through the major aspects of Android development with friendly, concise examples. You should walk away with a solid understanding of the necessary design patterns, frameworks, and APIs for producing a polished Android app. If you would like to follow along with the sample code, it can be found here.
Chapter 1 Setting Up
Before we start writing any code, our first task is to set up a development environment. The major components necessary for building an Android app are as follows:
While it’s possible to use virtually any IDE or text editor to create apps, the easiest way to get started with the Android platform is the official Android Software Development Kit (SDK), which contains all of these components in a single convenient download.
The Android SDK
The Android SDK (available for OS X, Windows, and Linux) includes the Eclipse IDE with the Android Developer Tools (ADT) plugin, along with an emulator, a graphical layout editor, and some other useful features. This is also the development environment that we’ll be using in this book, so go ahead and download it now so you can follow along.
Installation
After the download has completed, unzip the file and open the eclipse folder. It should contain an Eclipse executable that you can launch to start the IDE. You’ll be prompted to select a workspace folder, and then Eclipse should be ready to go. And that’s it for installation!
Creating a Project
Let’s jump right in by creating a new Android project. On the File menu, click New. In the resulting wizard, select Android Application Project.
Figure 2: Creating a new Android project
This will prompt you for some information about your new project:
The remaining fields define important platform requirements, and you can leave them all at their default values. Your configuration should look like the following when you’re done:
Figure 3: Configuring a new Android project
The next two windows ask you about some other miscellaneous details and the app’s icon. You can leave all of them at their default values. Finally, you’ll come to the following window asking if you want to create an activity:
Figure 4: Creating an initial activity
We’ll talk about activities in great detail next chapter, but all you need to know for now is that an activity represents a single screen of your application. We want to have something to look at initially, so make sure Create Activity is checked, then select Blank Activity to specify an empty screen. In the next window, you can use the default MainActivity and activity_main values for the Activity Name and Layout Name fields (again, we’ll discuss layouts in the next chapter). Click Finish to create a brand new Eclipse project.
Setting Up the Emulator
Unfortunately, we can’t immediately compile the template project to see what it does. First, we need to set up a device on which to test our new app. Android is designed to let you run a single application on devices of wildly differing dimensions and capabilities, making it a very efficient platform for porting apps from smartphones to tablets to anything in between. The Android Virtual Device Manager included in the SDK allows you to emulate virtually any device on the market.
To view the list of emulated devices, navigate to Window and select Android Virtual Device Manager. This window makes it easy to see how your application behaves on all sorts of Android devices, test different screen resolutions and dimensions, and experiment with various device capabilities (e.g., hardware keyboards, cameras, storage capacity).
To create an emulated device for our project, click New... and use GalaxyNexus for the AVD Name, then select Galaxy Nexus from the Device dropdown menu, and leave everything else as the default. For development purposes, it’s also a good idea to check the Use Host GPU to use your computer’s GPU, since emulating animations can be quite slow and clunky. Your configuration should resemble the following:
Figure 5: Creating a new emulated device
After clicking OK, you should find your device in the Android Virtual Device Manager window. To start the emulator, select the GalaxyNexus item, and click Start. Leave the launch options at their default values, and click Launch. This will start spinning up the emulator, which looks something like the following:
Figure 6: The Android device emulator
The emulator has to boot up the Android operating system (just like a real device), so you might be staring at that Android logo for a while before the emulator is actually ready to use. When it is finally ready, you’ll see the typical Android home screen, and you can click around to launch apps and explore the emulated device:
Figure 7: The emulator after it’s ready to use
Since it takes so long to boot, you’ll want to keep the emulator running as you start writing code (Eclipse can re-launch the application on the emulator without restarting it).
Compiling the Application
We’re finally prepared to compile the sample project. Back in Eclipse, make sure one of the source files is selected in the Package Explorer, then click Run, select Run as, and choose Android Application. After taking a moment to compile, you should see your first Android app in the device emulator. As you can see, the default template contains a single text field that says “Hello world!”
Figure 8: The compiled template project
In the next chapter, we’ll learn how to change the contents of this text field, add other UI components, and organize a simple Android application.
Chapter 2 Hello, Android
In this chapter, we’ll discover the fundamental design patterns of all Android applications. We’ll learn how to work with activities, display UI elements by editing XML layout files, handle button clicks, and switch between activities using intent objects. We’ll also learn about best practices for representing dimension and string values for maximum portability.
Each screen in an Android app is represented by a custom subclass of Activity. The subclass defines the behavior of the activity, and it’s also responsible for loading user interface from an XML layout file. Typically, this XML layout file is where the entire interface for a given activity is defined. To display text fields, buttons, images, and other widgets to the user, all you need to do is add XML elements to the layout file.
Intent objects are used to switch between the various activities that compose your app. For example, when the user clicks a button to navigate to another screen, you create an Intent object and pass the destination activity to it. Then, you “execute” the intent to tell Android to switch to the next page. This is the general pattern for building up a multi-screen application.
This chapter explains how all these android architecture components interact using hands-on examples. You can follow along with the empty Android project that you created in the previous chapter, or you can view the completed code in the HelloAndroid application included with the sample code for this book.
App Structure Overview
Let’s start by taking a look at the files and directories our template project created for us. It may look like there are a lot of files in Eclipse’s Package Explorer, but don’t be overwhelmed—there are only three items that you need to worry about:
The manifest and source directory are relatively straightforward, however the resource folder calls for a bit more explanation. If you expand this folder in the Package Explorer, you’ll find three types of subdirectories: drawable/, layout/, and values/. The drawable/ folders contain all of the graphics for your application, which can be either image files or special XML files defining shapes. The layout/ directory stores the UI of each screen displayed by your application, and the values/ folder contains lists of strings that are utilized by the UI.
Now, the interesting part is what comes after the hyphen. This portion of the folder name is a qualifier that tells the system when to use the contained resources. For example, images in drawable-hdpi/ will be displayed when the host device has a high-density screen (~240dpi), whereas devices with low-density screens (~120dpi) will use the images in drawable-ldpi/.
By simply placing high-resolution images and low-resolution images in the appropriate folders, your app will be available to both types of devices with no changes to your code. Similarly, your app can be ported to other languages by appending en, es, fr, ar, or any other language code after the values/ subdirectory. In this way, the res/ directory makes it very easy to support new devices and reach new audiences.
Creating a User Interface
Android apps use XML to define their user interfaces. Each XML element in a layout file represents either a ViewGroup or a View object. ViewGroups are invisible containers for other View objects, and their main job is to arrange child views (or nested view groups) into a pleasing layout. View objects are visible UI components like text fields, buttons, and tables. To configure the properties of a view or view group, you edit the attributes of the corresponding XML element.
The template project we used comes with a default layout called activity_main.xml, which you should find in the res/layout/ directory. When you double-click the file, ADT displays the graphical UI editor by default. While you can use this to visually edit the underlying XML, for this book, we’ll be directly editing the XML markup to gain an in-depth understanding of how Android user interfaces work. To display the raw XML, click the activity_main.xml tab in the bottom-left of Eclipse’s editing area, highlighted in orange as you can see in the following figure:
Figure 9: The raw XML tab for the main layout
After clicking this tab, you’ll find the XML that defines the current layout. It should look something like the following:
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
As you can see, this defines two elements: <RelativeLayout> and <TextView>. RelativeLayout is a subclass of ViewGroup that defines the position of its children relative to each other. TextView is a subclass of View that represents a standard text field component. We’ll survey the most common UI elements and later in this book.
All of the attributes in the android namespace determine various properties of the associated element. For example, android:layout_width="match_parent" makes the RelativeLayout stretch to the same size as its parent (in this case, the main window of the app). The available attributes and values for each type of element are listed in the documentation for the corresponding class (e.g., View, ViewGroup, RelativeLayout, TextView). The value of android:text is a reference to a string resource, which we’ll explain in a moment.
Adding a Button
But first, we’re going to simplify the default layout a bit and change it to a single button, centered on the screen. Replace the existing activity_main.xml with the following:
<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:gravity="center"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_next" />
</RelativeLayout>
We’ve done two things here. First, we replaced the <RelativeLayout>’s padding attributes with android:gravity. This tells it to center all of its child views. Second, we changed the <TextView> element to a <Button> and
Verlag: BookRix GmbH & Co. KG
Tag der Veröffentlichung: 01.02.2016
ISBN: 978-3-7396-3490-6
Alle Rechte vorbehalten