android ui fundamentals - develop & design

Download Android UI Fundamentals - Develop & Design

If you can't read please download the document

Upload: jairen1o0

Post on 01-Dec-2015

302 views

Category:

Documents


0 download

TRANSCRIPT

Document

Jason OstranderAndroid UIFundamentalsDevelopandDesIgN

Jason OstranderAndroid UIFundamentalsDevelopandDesIgn

Android UI Fundamentals: Develop and DesignJason OstranderPeachpit Press1249 Eighth StreetBerkeley, CA 94710510/524-2178510/524-2221 (fax)Find us on the Web at www.peachpit.comTo report errors, please send a note to [email protected] Press is a division of Pearson Education.Copyright 2012 by Jason OstranderEditor: Clifford ColbyDevelopment editor: Robyn ThomasProduction editor: Myrna VladicCopyeditor: Scout FestaTechnical editor: Jason LeBrunCover design: Aren Howell StraigerInterior design: Mimi HeftCompositor: Danielle FosterIndexer: Valerie Haynes PerryNotice of RightsAll rights reserved. No part of this book may be reproduced or transmitted in any form by any means,electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of thepublisher. For information on getting permission for reprints and excerpts, contact [email protected] of LiabilityThe information in this book is distributed on an As Is basis without warranty. While every precaution hasbeen taken in the preparation of the book, neither the author nor Peachpit shall have any liability to anyperson or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly bythe instructions contained in this book or by the computer software and hardware products described in it.TrademarksAndroid is a trademark of Google Inc., registered in the United States and other countries. Many of thedesignations used by manufacturers and sellers to distinguish their products are claimed as trademarks.Where those designations appear in this book, and Peachpit was aware of a trademark claim, the designa-tions appear as requested by the owner of the trademark. All other product names and services identifiedthroughout this book are used in editorial fashion only and for the benefit of such companies with nointention of infringement of the trademark. No such use, or the use of any trade name, is intended toconveyendorsement or other affiliation with this book.ISBN 13: 978-0-321-81458-6ISBN 10:0-321-81458-49 8 7 6 5 4 3 2 1Printed and bound in the United States of America

To my lovely wife, Susan,who tirelessly supports me in all of my adventures.

IvAndroid Ui FUndAmentAls: develop And designI could write an entire book thanking people for their help along the way. Instead,Ill have to settle for this short paragraph:Thanks to Chris H. for pushing me to consider writing a book and giving meendless encouragement and support. To Cliff C. for giving me the chance to writethis book. To Robyn T. for keeping me on schedule despite my best efforts. ToJBL for fixing my code and rocking a mean bass guitar. To Scout F. and Myrna V.for working tirelessly when I was late getting chapters to them. To Lucas D. andRob S. for reading early chapters and giving me valuable feedback. To the entireteam at doubleTwist for their dedication to making great Android software. Tothe Android team at Google for creating a great platform. To my family for theircontinuing support despite my dropping off the face of the earth. To Peachpit forgiving me the opportunity to write this for you. And to you, the reader, for givingme the chance to teach you in whatever small way I can.BioJason Ostrander is a web and mobile software developer working at Silicon Valleystartup doubleTwist, where he makes syncing media to Android phones simple.Prior to that, he solved networking problems at energy management startupSentilla and defense company Northrop Grumman. Jason holds an MS in electricalengineering from UCLA. He lives with his wife in San Franciscos Mission District,where he spends his time searching for the perfect chile relleno.Acknowledgments

Contentsv Introduction ..........................................................viiiWelcome to Android....................................................xPart 1BAsIc ANDROID UIChapter 1GeTTING sTARTeD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Hello World .............................................................4Basic Structure of an Android App .....................................9Android UI Basics .....................................................14Tools ...................................................................22Wrapping Up ..........................................................32Chapter 2cReATING YOUR FIRsT APPLIcATION . . . . . . . . . . . . . . . . . . . . . . . . . .34Creating an App .......................................................36Getting Started with Android Views ..................................37Arranging Views .......................................................41Displaying a List .......................................................52Understanding Activities ..............................................57Preventing ANRs ......................................................64Finishing the TimeTracker App .......................................71Wrapping Up ..........................................................73Chapter 3GOING FURTheR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74Supporting Multiple Screen Sizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .76Handling Notifications ................................................84Handling Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .92Creating Menus ....................................................... 96Implementing the Time Tracker .................................... 102Wrapping Up .........................................................107contents

vIAndroid Ui FUndAmentAls: develop And design Part 2The vIew FRAmewORkChapter 4BAsIc vIews . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .110Creating a Basic Form ................................................112Displaying Images ....................................................124Creating Maps and Displaying Websites .............................130Wrapping Up .........................................................136Chapter 5ReUsABLe UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138Abstracting Your Layouts............................................ 140Abstracting Styles and Themes ......................................148Using Fragments......................................................153Wrapping Up .........................................................162Chapter 6NAvIGATION AND DATA LOADING . . . . . . . . . . . . . . . . . . . . . . . . . . . .164Introducing the Action Bar ...........................................166Navigating Your App..................................................172Loading Data into Views..............................................181Wrapping Up .........................................................186Chapter 7ANDROID wIDGeTs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .188Creating a Basic Widget ............................................. 190Creating a Collection Widget ........................................206Wrapping Up .........................................................211

ContentsvII Part 3ADvANceD UI DeveLOPmeNTChapter 8hANDLING GesTURes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214Listening to Touch Events ............................................216Responding to Gestures ............................................. 224Wrapping Up ........................................................ 229Chapter 9ANImATION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230Creating Drawable Animations...................................... 232Creating View Animations ...........................................235Creating Property Animations ...................................... 246Wrapping Up ........................................................ 255Chapter 10cReATING cUsTOm vIews . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256Understanding How Android Draws Views ......................... 258Creating a Custom View ............................................. 259Adding Custom Attributes to Your Custom Views . . . . . . . . . . . . . . . . . . .267Creating Compound Components....................................274Wrapping Up ........................................................ 279Chapter 11cReATING ADvANceD GRAPhIcs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280Using Canvas ........................................................ 282Using RenderScript .................................................. 289Using OpenGL ....................................................... 294Wrapping Up .........................................................301Chapter 12LOcALIzATION AND AccessIBILITY . . . . . . . . . . . . . . . . . . . . . . . . . . 302Making Your App Available in Multiple Languages . . . . . . . . . . . . . . . . . 304Making Your App Accessible ........................................309Wrapping Up .........................................................315Index..................................................................316

vIIIAndroid Ui FUndAmentAls: develop And designThere is a revolution happening in the technology industry. Touchscreen interfaces,combined with low-cost and ubiquitous smartphones, have created a perfect stormfor disruptive innovation. Android is at the forefront of this change, bringing a freeand open-source platform on which developers can create the next generation ofapplications. With free development tools and an open market, anyone can developapplications that reach a worldwide market. But why choose to develop for Android?Android now runs on the majority of smartphones in the United States. Andits quickly expanding into new markets and device types. The last year has seenthe introduction of hundreds of Android-based tablets, including the hit KindleFire. Google has ported Android to TVs with its Google TV platform, and manymanufacturers are beginning to ship TVs with Android built in. Boeing has selectedAndroid as the entertainment platform for its new Dreamliner jet. Ford is integrat-ing Android into its in-dash SYNC entertainment system. And Android is quicklygaining traction in the developing world, especially in Africa, where the need forlow-cost handsets is greatest.Yet for all of the platforms promise, the majority of Android applications stilllack the visual polish of their iOS counterparts. This book aims to address thatissue by providing developers with a solid foundation for building app UIs. It willcover the basics of UI development on Android, teach best practices for creatingflexible layouts, and give you tips on how to optimize your UI for smooth, fluidperformance. I created this book in the hope that it will help developers to createbeautiful applications.Who am I? Ive been developing software professionally for almost ten years,and Ive focused on embedded and mobile software for the last five. In my day job,I work for one of the top Android development companies and write code thatmillions of people use every day.Android development can be difficult at times, and the challenges of supportingsuch a diversity of devices can be daunting. But with a good idea, a solid under-standing of the framework, and a little persistence, anyone can create a great appthat is used by millions of people.I hope youll enjoy reading this book as much as I enjoyed writing it for you.introduction

introdUCtionIxWho this Book is ForThis book is aimed at beginning Android developers who are interested in creatinggreat user interfaces. You are expected to know basic Java programming and XMLsyntax. The focus of this book is on UI. While you dont need to have experiencewriting Android software, many basic Android concepts are only described inpassing. It will help you to have a rudimentary knowledge of Android development.Who this Book is Not ForThis book is not a general introduction to programming for Android. While it isintended for beginning Android developers, the focus is on user interface toolsand programming. In particular, this book will not cover basic Android conceptssuch as intents, services, or content providers. Further, this book will not be anintroduction to the Java programming language or to XML. You should know howto program and how to read XML.hoW You Will learNThroughout this book, youll learn by creating an actual app, a simple timetracker. Each chapter includes detailed examples of real Android code that youwill compile and run. All code for the book can be found at the books website:www.peachpit.com/androiduifundamentals.What You Will learNYoull learn how to create user interfaces for Android applications. From the mostbasic concepts, like activities and views, all the way to advanced graphics usingRenderScript, this book covers everything you will use to build the user interfaceof your apps.a Note aBout aNdroid VersioNsThis book was written to Android version 4 APIs and best practices, but it is com-patible back to Android version 2.2. When relevant, notes and tips are included toindicate when an API is deprecated or no longer appropriate. The Android com-patibility library, a package of classes that back-port several newer features, willbe used throughout the book.

xAndroid Ui FUndAmentAls: develop And design welcometoAndroidThroughout this book, youll be writing your code using the Eclipse integrated develop-ment environment (IDE). Youll need to install the Android software development kit(SDK), along with the Android Developer Tools (ADT) plugin. This setup includes severalother utilities to help you develop and test your application. Aside from the SDK, none ofthese tools are required, but they will make your application development easier.the toolsThe following tools are used throughout this book to build, test, and analyze yourapplications.Android sdKThe Android SDK isrequired to build anddeploy Android applica-tions. The SDK containsthe tools youll use to testand debug your applica-tion. It also containstools for creating flexiblelayouts. You can downloadthe Android SDK at http://developer.android.com/.eClipseEclipse is the recom-mended IDE for Androiddevelopment and is theonly IDE officially sup-ported by Google. Googlepublishes a plugin calledAndroid Developer Toolsthat integrates withEclipse and providesfeatures like a drag-and-drop interface builder. Youare not required to useEclipse, as the AndroidSDK fully supports com-mand-line development.Throughout this book,however, it is assumedyou are using Eclipse. Youcan download Eclipse atwww.eclipse.org.

WelCome to AndroidxIAndroid sdKmAnAgerThe Android SDK Manageris used to download andinstall the Android SDK.You will also use the SDKManager to install add-onfeatures like sample code,third-party emulators,and the compatibilitylibrary. The Android SDKManager can also beused to create and launchemulated Android devices,called Android VirtualDevices. The Android SDKManager can be found inthe SDKtools/directoryasandroid.HierArCHy vieWerThis tool displays agraphical representationof your layout hierarchyand can help you debuglayout performanceissues by spotting overlycomplex layouts. Its alsoa good tool for under-standing how Androidlayout works. You canfind this tool in theSDKtools/directory ashierarchyviewer.ddmsThe Dalvik Debug MonitorServer (DDMS) is usedto debug applicationperformance issues. Itprovides Java heap usage,running thread counts,and object allocationtracking. You also use itto take screen shots. TheDDMS tool is built intoEclipse through the ADTor can be run standalonefrom thetools/directoryof the SDK.

This page intentionally left blank

Part 1BASIcAndroid ui

1GETTInGstArted

3Android is a powerful mobile operating system, builtusing a combination of the Java programming languageand XML-based layout and configuration files. This chap-ter introduces the Android development environment, walksthrough the basic Hello World application, and covers the Androidtools, with an emphasis on the user interface (UI) tools available inthe Android Developer Tools (ADT) plugin. In this chapter youllcreate a Hello World application; learn the Android project layoutand purpose of each file and folder; learn basic Android UI con-cepts like theActivityclass and XML layouts; and discover thetools available for creating user interfaces in Android.

Before you create a basic Hello World app, you must download and install theAndroid developer tools available at developer.android.com. You will need to installthe Android software development kit (SDK), Eclipse, and the ADT plugin. Followthe directions provided on the developer website to set up the Eclipse develop-ment environment. All examples in this book use Android SDK Release 13 and theEclipse Helios release.When ready, create the Hello World application using the following steps:1.Start Eclipse.2.Open the Java perspective by choosing Window > Open Perspective > Java.3.Choose File > New > Android Project.4.Leave all the defaults. Name the projectExampleand click Next (Figure 1.1).FIGURe 1 .1The Android projectcreation wizardHelloWorld4ChaPter 1getting stArted

5.Set the Build Target option to Android 4.0 (Figure 1.2). Youll build toAndroid version 4.0 (API version 15) for all code in this book. Click Next.6.Enter the package namecom.example(Figure 1.3).7.Click Finish, and the project will be created for you.8.Run your app by right-clicking the Example project in the left-hand PackageExplorer pane and selecting Run As > Android Application.FIGURe 1 .2The Androidproject build target (left)FIGURe 1 .3The Androidproject properties (right)Hello World5

9.Select Yes when prompted to create a new Android Virtual Device (AVD).This will open the AVD Manager (Figure 1.4). Click the New button andconfigure it as shown inFigure 1.5. Click Create AVD when finished.10.In the AVD Manager, select the AVD you just created and click Start. Whenprompted, click Launch. The emulator will start.11.Once the emulator has loaded, close the AVD Manager, and the AndroidDevice Chooser will open (Figure 1.6).Select the running emulator, andclick OK.FIGURe 1 .4The AVD Manager6ChaPter 1getting stArted

FIGURe 1 .5Android VirtualDevice (AVD) creation dialogFIGURe 1 .6The Android Device ChooserHello World7

Congratulations, you now have a running Android application (Figure 1.7). runningtheexAmpleaPP oN apHoneIf you want to run the Example app on your phone, follow these steps:1 .On your phones home screen, press Menu > Settings > Applications. Selectthe Unknown sources checkbox to enable installation from your computer.2 .Open the Development menu and select the USB debugging checkbox.3 .Plug your phone into your computer.4 .now close the emulator on your computer and run your applicationagain. It should install on your phone. If the Android Device chooserdialog appears, select your device from the list.FIGURe 1 .7Hello World apprunning on Android emulator8ChaPter 1getting stArted

BasiCstructureoFaNAndroid AppThe Eclipse IDE created an initial project structure for you when you started anew Android project. This project contains all the elements you need to buildyour application, and you should generally place all your work in this project. Itspossible to create a library project for code-sharing between applications, but formost apps this is unnecessary. This section covers the basic structure of the projectfolder and where you should place your code, layouts, and resources.Folder struCtureExpand the Example project folder in the Package Explorer and take a look at theproject structure. Android uses a standard Java application layout.Table 1.1sum-marizes the project structure.TABLe 1 .1Android Project Folder Structure itemexPlaNatioNsrc/This folder contains your apps Java source code. It follows the standard Java packageconventions. For example, acom.example.Fooclass would be located in the foldersrc/com/example/Foo.java.res/This folder contains all the resources of your app and is where you declare the layoutusing XML. This folder contains all layout files, images, themes, and strings.gen/This folder is auto-generated when you compile the XML layouts inres/. It usuallycontains only a single file,R.java.This file contains the constants you need to referencethe resources in theres/folder. Do not edit anything in this folder.assets/This folder contains miscellaneous files needed by your application. If your app needs abinary asset to function, place it here. To use these files, you need to open them usingthe Java File application programming interfaces (APIs).AndroidManifest.xmlThe manifest contains essential information about your app that the Android systemneeds. This includes the activites and services your app uses, the permissions it requires,any intents it responds to, and basic info like the app name.default.propertiesLists the Android API build target.BAsiC strUCtUre oF An Android App9

aNdroid maNiFestThe Android manifest contains all the information about your apps structure andfunctionality. It includes all the activities your app uses, the services it provides, anydatabase content it makes available via a content provider, and any intents it processes.