Android Programming: The Big Nerd Ranch Guide by Bill Phillips and Brian Hardy Copyright © 2013 Big Nerd Ranch, Inc All rights reserved Printed in the United States of America This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise For information regarding permissions, contact Big Nerd Ranch, Inc 1989 College Ave Atlanta, GA 30317 (404) 478-9005 http://www.bignerdranch.com/ book-comments@bignerdranch.com The 10-gallon hat with propeller logo is a trademark of Big Nerd Ranch, Inc Exclusive worldwide distribution of the English edition of this book by Pearson Technology Group 800 East 96th Street Indianapolis, IN 46240 USA http://www.informit.com The authors and publisher have taken care in writing and printing this book but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein Android, Dalvik, Google Play, Google TV, Google Chrome, Chrome, Gmail, and Nexus are trademarks of Google Inc Eclipse is a trademark of Eclipse Foundation, Inc Java, and all Javabased trademarks are trademarks of Oracle Corporation and/or its affiliates Mac is a trademark of Apple Inc., registered in the U.S and other countries Windows is a registered trademark of Microsoft Corporation in the United States and other countries Linux is the registered trademark of Linus Torvalds in the U.S and other countries Flickr is a registered trademark of Yahoo! Inc Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals Print ISBN-10 0321804333 Print ISBN-13 978-0321804334 CuuDuongThanCong.com First Edition, first printing, March 2013 Release K.1.1.1 CuuDuongThanCong.com Dedication For Donovan May he live a life filled with activities and know when to use fragments —B.H CuuDuongThanCong.com Acknowledgments We feel a bit sheepish having our names on the cover of this book The truth is that without an army of collaborators, this book could never have happened We owe them all a debt of gratitude Chris Stewart and Owen Matthews contributed great foundational content for several chapters Our co-instructors, Chris Stewart and Christopher Moore We thank them for their patience in teaching work-in-progress material, their suggestions and corrections for that material, and their consultation when we were considering sweeping changes Our coworkers Bolot Kerimbaev and Andrew Lunsford Their feedback was instrumental in our decision to highlight the use of fragments Our technical reviewers, Frank Robles, Jim Steele, Laura Cassell, Mark Dalrymple, and Magnus Dahl, helped us find and fix flaws Thanks to Aaron Hillegass Aaron’s faith in people is one of the great and terrifying forces of nature Without it, we would never have had the opportunity to write this book, nor would we ever have completed it (He also gave us money, which was very friendly of him.) Our editor, Susan Loper, has an amazing ability to turn our programmery ramblings and bad jokes into thoughtful, concise prose And better jokes Without her help, this would not have been a fun book to read She taught us everything we know about clear and approachable technical writing Thanks to NASA Our little book seems small and silly in comparison to exploring the solar system Ellie Volckhausen, who designed the cover Chris Loper at IntelligentEnglish.com, who designed and produced the print book and the EPUB and Kindle versions His DocBook toolchain made life much easier, too The folks at Facebook, who gave us so much fantastic feedback on the course Finally, thanks to our students We wish that we had room to thank every single student who gave us a correction or opinion on the book as it was shaping up It is your curiosity we have worked to satisfy, your confusions we have worked to clarify Thank you CuuDuongThanCong.com Table of Contents Learning Android Prerequisites How to Use This Book How This Book Is Organized Challenges Are you more curious? Code Style Typographical Conventions Using an eBook The Necessary Tools The ADT Bundle Your First Android Application App Basics Creating an Android Project Navigating in Eclipse Laying Out the User Interface The view hierarchy Widget attributes Creating string resources Previewing the layout From Layout XML to View Objects Resources and resource IDs Wiring Up Widgets Organizing imports Getting references to widgets Setting listeners Running on the Emulator For the More Curious: Android Build Process Android build tools Android and Model-View-Controller Creating a New Class Generating getters and setters Model-View-Controller and Android Benefits of MVC Updating the View Layer Updating the Controller Layer Running on a Device Connecting your device Configuring your device for development Adding an Icon Adding resources to a project Referencing resources in XML CuuDuongThanCong.com Challenges Challenge: Add a Listener to the TextView Challenge: Add a Previous Button Challenge: From Button to ImageButton The Activity Lifecycle Logging the Activity Lifecycle Making log messages Using LogCat Rotation and the Activity Lifecycle Device configurations and alternative resources Saving Data Across Rotation Overriding onSaveInstanceState(Bundle) The Activity Lifecycle, Revisited For the More Curious: Testing onSaveInstanceState(Bundle) For the More Curious: Logging Levels and Methods Debugging Android Apps The DDMS Perspective Exceptions and Stack Traces Diagnosing misbehaviors Logging stack traces Setting breakpoints Using exception breakpoints File Explorer Android-Specific Debugging Using Android Lint Issues with the R class Your Second Activity Setting Up a Second Activity Creating a new layout Creating a new activity subclass Declaring activities in the manifest Adding a Cheat button to QuizActivity Starting an Activity Communicating with intents Passing Data Between Activities Using intent extras Getting a result back from a child activity How Android Sees Your Activities Challenge Android SDK Versions and Compatibility Android SDK Versions Compatibility and Android Programming Honeycomb was big Minimum SDK version Target SDK version CuuDuongThanCong.com Build SDK version Adding code from later APIs safely Using the Android Developer Documentation Challenge: Reporting the Build Version UI Fragments and the Fragment Manager The Need for UI Flexibility Introducing Fragments Starting CriminalIntent Creating a new project Fragments and the support library Creating the Crime class Hosting a UI Fragment The fragment lifecycle Two approaches to hosting Defining a container view Creating a UI Fragment Defining CrimeFragment’s layout Creating the CrimeFragment class Adding a UI Fragment to the FragmentManager Fragment transactions The FragmentManager and the fragment lifecycle The Reason All Our Activities Will Use Fragments For the More Curious: Developing for Honeycomb, ICS, Jelly Bean, and Beyond Creating User Interfaces with Layouts and Widgets Upgrading Crime Updating the Layout Wiring Widgets More on XML Layout Attributes Styles, themes, and theme attributes Screen pixel densities and dp and sp Android’s design guidelines Layout parameters Margins vs padding Using the Graphical Layout Tool Adding a new widget Editing attributes in properties Reorganizing widgets in the outline view Updating child layout parameters How android:layout_weight works Summary of graphical layout tool Widget IDs and multiple layouts Challenge: Formatting the Date Displaying Lists with ListFragment Updating CriminalIntent’s Model Layer Singletons and centralized data storage CuuDuongThanCong.com Creating a ListFragment An Abstract Activity for Hosting a Fragment A generic fragment-hosting layout An abstract Activity class ListFragment, ListView, and ArrayAdapter Creating an ArrayAdapter Responding to list item clicks Customizing List Items Creating the list item layout Creating an adapter subclass 10 Using Fragment Arguments Starting an Activity from a Fragment Putting an extra Retrieving an extra Updating CrimeFragment’s view with Crime data The downside to direct retrieval Fragment Arguments Attaching arguments to a fragment Retrieving arguments Reloading the List Getting Results with Fragments 11 Using ViewPager Creating CrimePagerActivity Laying out views in code ViewPager and PagerAdapter Integrating CrimePagerActivity FragmentStatePagerAdapter vs FragmentPagerAdapter For the More Curious: How ViewPager Really Works 12 Dialogs Creating a DialogFragment Showing a DialogFragment Setting a dialog’s contents Passing Data Between Two Fragments Passing data to DatePickerFragment Returning data to CrimeFragment Challenge: More Dialogs 13 Audio Playback Using MediaPlayer Adding Resources Defining the layout for HelloMoonFragment Manually resetting the app theme Creating HelloMoonFragment Using a Layout Fragment Audio Playback Wiring buttons to play and stop Challenge: Pausing Audio Playback CuuDuongThanCong.com For the More Curious: Playing Video Challenge: Playing Video in HelloMoon 14 Retained Fragments Retaining a Fragment Rotation and Retained Fragments Retained Fragments: As Nice as All That? Rotation Handling and onSaveInstanceState(Bundle) For the More Curious: Rotation Before Fragments 15 Localization Localizing Resources Default resources Configuration Qualifiers Prioritizing alternative resources Multiple qualifiers Finding the best-matching resources More Resource Rules and Regulations Resource naming Resource directory structure Testing Alternative Resources 16 The Action Bar Options Menus Defining an options menu in XML Creating the options menu Responding to options menu selections Enabling Ancestral Navigation Enabling the app icon Responding to the Up button An Alternative Menu Item Creating an alternative menu file Toggling the menu item title “Just one more thing ” Challenge: An Empty View for the List 17 Saving and Loading Local Files Saving and Loading Data in CriminalIntent Saving crime data to a JSON file Loading crimes from the filesystem Challenge: Use External Storage For the More Curious: The Android Filesystem and Java I/O Accessing files and directories 18 Context Menus and Contextual Action Mode Defining a Context Menu Resource Implementing a Floating Context Menu Creating the context menu Registering for the context menu Responding to an action CuuDuongThanCong.com Implementing Contextual Action Mode Enabling multiple selection Action mode callbacks in a list view Changing activated item backgrounds Implementing contextual action mode in other views Compatibility: Fallback or Duplicate? Challenge: Deleting from CrimeFragment For the More Curious: ActionBarSherlock Challenge: Using ActionBarSherlock Basic ABS integration in CriminalIntent More advanced integration Even more advanced integration 19 Camera I: Viewfinder Creating the Fragment Layout Creating CrimeCameraFragment Creating CrimeCameraActivity Adding activity and camera permissions to the manifest Using the Camera API Opening and releasing the camera SurfaceView, SurfaceHolder, and Surface Determining preview size Starting CrimeCameraActivity from CrimeFragment For the More Curious: Running Activities from the Command Line 20 Camera II: Taking Pictures and Handling Images Taking a Picture Implementing Camera callbacks Setting the picture size Passing Data Back to CrimeFragment Starting CrimeCameraActivity for a result Setting a result in CrimeCameraFragment Retrieving filename in CrimeFragment Updating the Model Layer Adding a Photo class Giving Crime a photo property Setting the photo property Updating CrimeFragment’s View Adding an ImageView Image handling Showing Larger Image in a DialogFragment Challenge: Crime Image Orientation Challenge: Deleting Photos For the More Curious: Deprecation in Android 21 Implicit Intents Adding Buttons Adding a Suspect to the Model Layer CuuDuongThanCong.com model objects, Model-View-Controller and Android motion events, handling, Handling Touch Events MotionEvent actions, Handling Touch Events class, Handling Touch Events getAction(), Handling Touch Events MVC (Model-View-Controller), Model-View-Controller and Android N namespace, Android XML, The view hierarchy navigateUpFromSameTask(…) (NavUtils), Responding to the Up button navigation types of, Enabling Ancestral Navigation NavUtils for ancestral navigation, Responding to the Up button navigateUpFromSameTask(…), Responding to the Up button network, checking availability of, Safe background networking networking (HTTP), HTTP & Background Tasks, Networking Basics, Asking permission to network, Beyond the main thread NetworkOnMainThreadException, You and Your Main Thread newInstance(…) (Fragment), Attaching arguments to a fragment 9-patch images, Using 9-Patch Images Notification, Notifications NotificationManager, Notifications notifications, Notifications notify(…) (NotificationManager), Notifications NullPointerException, Exceptions and Stack Traces O onActionItemClicked(…) (ActionMode.Callback), Action mode callbacks in a list view onActivityResult(…) (Activity), Sending back an intent onActivityResult(…) (Fragment), Passing Data Between Two Fragments OnCheckedChangeListener interface, Wiring Widgets onClick(View) (onClickListener), Using anonymous inner classes OnClickListener interface, Setting listeners onContextItemSelected(…) (Fragment), Implementing a Floating Context Menu, Responding to an action onCreate(Bundle) (Activity), From Layout XML to View Objects, The Activity Lifecycle, Making log messages onCreate(…) (Fragment), Implementing fragment lifecycle methods onCreate(…) (SQLiteOpenHelper), Storing Runs and Locations in a Database onCreateActionMode(…) (ActionMode.Callback), Action mode callbacks in a list view onCreateContextMenu(…) (Fragment), Implementing a Floating Context Menu CuuDuongThanCong.com onCreateDialog(…) (DialogFragment), Creating a DialogFragment onCreateLoader(…) (LoaderCallbacks), Loading the List of Runs onCreateOptionsMenu(…) (Action), Creating the options menu onCreateOptionsMenu(…) (Fragment), Creating the options menu onCreateView(…) (Fragment), Implementing fragment lifecycle methods onDestroy() (Activity), The Activity Lifecycle onDestroyActionMode(…) (ActionMode.Callback), Action mode callbacks in a list view onDraw(…) (View), Rendering Inside onDraw(…) onHandleIntent(…) (IntentService), Creating an IntentService onItemCheckedStateChanged(…) (MultiChoiceModeListener), Action mode callbacks in a list view onListItemClick(…) (ListFragment), Responding to list item clicks onLoaderReset(…) (LoaderCallbacks), Loading the List of Runs onLoadFinished(…) (LoaderCallbacks), Loading the List of Runs onLocationChanged(…) (LocationListener), Locations and the LocationManager onOptionsItemSelected(…) (Fragment), Responding to options menu selections OnPageChangeListener interface (ViewPager), Integrating CrimePagerActivity onPageScrolled(…) (ViewPager), Integrating CrimePagerActivity onPageScrollStateChanged(…) (ViewPager), Integrating CrimePagerActivity onPageSelected(…) (ViewPager), Integrating CrimePagerActivity onPause() (Activity), The Activity Lifecycle onPostExecute(…) (AsyncTask), From AsyncTask Back to the Main Thread onPrepareActionMode(…) (ActionMode.Callback), Action mode callbacks in a list view onPrepareOptionsMenu(…) (Fragment), Updating options menu items onProgressChanged(…) (WebChromeClient), Using WebChromeClient to spruce things up onProgressUpdate(…) (AsyncTask), For the More Curious: More on AsyncTask onReceivedTitle(…) (WebChromeClient), Using WebChromeClient to spruce things up onRestoreStateInstance(…) (View), Challenge: Rotations onResume() (Activity), The Activity Lifecycle, Reloading the List onResume() (FragmentManager), Reloading the List onSaveInstanceState(…), Rotation Handling and onSaveInstanceState(Bundle) onSaveInstanceState(…) (Activity, Saving Data Across Rotation, For the More Curious: Testing onSaveInstanceState(Bundle) onSaveInstanceState(…) (Fragment), Implementing fragment lifecycle methods, Retained Fragments onSaveStateInstance() (View), Challenge: Rotations onSearchRequested() (Activity), Creating a search interface onStart() (Activity), The Activity Lifecycle onStop() (Activity), The Activity Lifecycle onTextChanged(…) (TextWatcher), Wiring widgets in a fragment onTouchEvent(…) (View), Handling Touch Events OnTouchListener (View), Handling Touch Events onUpgrade(…) (SQLiteOpenHelper), Storing Runs and Locations in a Database open(…) (Camera), Opening and releasing the camera openConnection() (URL), Networking Basics openFileOutput(…), Loading crimes from the filesystem options menus CuuDuongThanCong.com accessing on pre-Honeycomb, Creating the options menu android:showAsAction, Defining an options menu in XML compatibility and, Context Menus and Contextual Action Mode creating, Creating the options menu defined, Options Menus determining selected item, Responding to options menu selections populating with items, Creating the options menu pre/post-Honeycomb behavior, Creating the options menu responding to selections, Responding to options menu selections updating dynamically, Updating options menu items updating dynamically (post Honeycomb), Updating options menu items organizing imports, Organizing imports, Using auto-complete OutputStream, Creating the CriminalIntentJSONSerializer class OutputStreamWriter, Creating the CriminalIntentJSONSerializer class overflow menu, Defining an options menu in XML @Override, Making log messages P PackageManager class, Checking for responding activities metadata and, Responding to the Up button queryIntentActivities(…), Checking for responding activities packages, naming, Creating an Android Project padding, Margins vs padding Paint, Rendering Inside onDraw(…) Parcelable, Challenge: Rotations parsing XML, Using XmlPullParser PendingIntent details, PendingIntent getBroadcast(…), Locations and the LocationManager getService(…), Delayed Execution with AlarmManager location updates and, Locations and the LocationManager persistent data with JSON, Saving and Loading Data in CriminalIntent using shared preferences, Simple persistence with shared preferences perspectives DDMS perspective, The DDMS Perspective Debug perspective, Setting breakpoints defined, The DDMS Perspective Java perspective, The DDMS Perspective resetting, The DDMS Perspective switching between, The DDMS Perspective PointF, Handling Touch Events post(…) (Handler), Passing handlers CuuDuongThanCong.com PreferenceManager getDefaultSharedPreferences(…), Simple persistence with shared preferences preferences (Eclipse), Generating getters and setters preloading, Challenge: Preloading and Caching processes, For the More Curious: Processes vs Tasks progress indicator hiding, Using WebChromeClient to spruce things up spinner type, Taking a Picture updating from background thread, For the More Curious: More on AsyncTask ProgressBar, Taking a Picture projects adding resources, Adding resources to a project configure, Creating an Android Project creating, Creating an Android Project gen directory, Resources and resource IDs layout, Creating an Android Project library, For the More Curious: ActionBarSherlock res/layout directory, Resources and resource IDs res/menu directory, Defining an options menu in XML res/raw directory, Adding Resources res/values directory, Resources and resource IDs setting package name, Creating an Android Project setting project name, Creating an Android Project src directory, From Layout XML to View Objects protection level values, More about protection levels publishProgress(…) (AsyncTask), For the More Curious: More on AsyncTask putCharSequence(…); (Bundle), Fragment Arguments putExtra(…) (Intent), Putting an extra putInt(…); (Bundle), Fragment Arguments putSerializable(…) (Bundle), Fragment Arguments Q queryIntentActivities(…) (PackageManager), Checking for responding activities R R, Resources and resource IDs randomUUID(), Creating the Crime class read() (InputStream), Networking Basics Recents button, Using LogCat recycle() (Bitmap), Unloading the image registerForContextMenu(…) (Fragment), Registering for the context menu RelativeLayout, Creating the list item layout release key, For the More Curious: Android Build Process CuuDuongThanCong.com release() (Camera), Opening and releasing the camera release() (MediaPlayer), Audio Playback remove(…) (FragmentTransaction), FragmentStatePagerAdapter vs FragmentPagerAdapter request code (Activity), Getting a result back from a child activity requestLocationUpdates(…) (LocationManager), Locations and the LocationManager res/layout directory, Resources and resource IDs res/menu directory, Defining an options menu in XML res/raw directory, Adding Resources res/values directory, Creating string resources, Resources and resource IDs ResolveInfo, Resolving an Implicit Intent resource IDs, Resources and resource IDs + prefix in, Resources and resource IDs, Creating the list item layout multiple layouts and, Widget IDs and multiple layouts syntax, Creating the list item layout resources (see also configuration qualifiers, drawables, layouts, menus, string resources) adding, Adding resources to a project alias, Using an alias resource alternative, Prioritizing alternative resources default, Default resources defined, Resources and resource IDs directory structure, Resource directory structure localizing, Localization location of, Resources and resource IDs naming requirements, Resource naming referencing in XML, Referencing resources in XML string, android:text styles, Cleaning Up with Styles restartLoader(…) (LoaderManager), Loaders and the LoaderManager result code (Activity), Setting a result retained fragments, Retaining a Fragment retainInstance property (Fragment), Retaining a Fragment, Rotation and Retained Fragments rotation activity lifecycle and, Rotation and the Activity Lifecycle before fragments, For the More Curious: Rotation Before Fragments onSaveInstanceState(…) and, Rotation Handling and onSaveInstanceState(Bundle) preventing, Adding activity and camera permissions to the manifest saving data across, Saving Data Across Rotation running on device, Running on a Device S s prefix for variable names, Generating getters and setters scale-independent pixel (see sp (scale-independent pixel)) screen orientation, Creating a landscape layout CuuDuongThanCong.com forcing, Adding activity and camera permissions to the manifest screen pixel density, Adding an Icon, Screen pixel densities and dp and sp, Screen density works differently screen size, determining, For the More Curious: More on Determining Device Size ScrollView, Adding Buttons SD card, Saving and Loading Local Files SDK versions (see also compatibility) build target, Build SDK version codenames, Android SDK Versions installing, Downloading earlier SDK versions listed, Android SDK Versions minimum required, Honeycomb was big target, Honeycomb was big updating, Downloading earlier SDK versions search configuration, Searchable activities configuring emulator for, Hardware search button coordinating with SearchManager service, Searchable activities hardware button, Creating a search interface how it works, How Search works integrating into app, Search intent filter, Searchable activities metadata, Searchable activities post Honeycomb, Using SearchView on Post-Android 3.0 program-initiated, Creating a search interface specifying details of, Challenges searchable activity, How Search works searchable.xml, Searchable activities SearchView bug, Using SearchView on Post-Android 3.0 class, Using SearchView on Post-Android 3.0 getSearchableInfo(…), Using SearchView on Post-Android 3.0 selector (XML element), Changing activated item backgrounds services adding to manifest, Creating an IntentService bound, Bound services lifecycle of, A service’s lifecycle locally bound, Local service binding non-sticky, Non-sticky services notifying user, Notifications purpose of, Background Services remotely bound, Remote service binding sticky, Sticky services setArguments(…) (Fragment), Attaching arguments to a fragment CuuDuongThanCong.com setChoiceMode(…) (ListView), Enabling multiple selection setClassName(…) (Intent), Creating Explicit Intents at Runtime setComponent(…) (Intent), Creating Explicit Intents at Runtime setContentView(…) (Activity), From Layout XML to View Objects setDisplayHomeAsUpEnabled(…) (ActionBar), Enabling the app icon setEmptyView(…) (AdapterView), Challenge: An Empty View for the List setHasOptionsMenu(…) (Fragment), Creating the options menu setJavaScriptEnabled(…) (WebSettings), The Harder Way: WebView setListAdapter(…) (ListFragment), Creating an ArrayAdapter setOffscreenPageLimit(…) (FragmentStatePagerAdapter), Integrating CrimePagerActivity setOnClickListener(…), Setting listeners setOnItemClickListener(…) (GridView), The Easy Way: Implicit Intents setOnTouchListener(…) (View), Handling Touch Events setPositiveButton(…) (AlertDialog.Builder), Creating a DialogFragment setPreviewDisplay(…) (Camera), SurfaceView, SurfaceHolder, and Surface setRepeating(…) (AlarmManager), Delayed Execution with AlarmManager setResult(…) (Activity), Setting a result, Sending back an intent, Getting Results with Fragments setRetainInstance(…) (Fragment), Retaining a Fragment setTargetFragment(…) (Fragment), Setting a target fragment setter methods (see getter and setter methods) setText(…) (TextView), Using intent extras setTitle(…) (AlertDialog.Builder), Creating a DialogFragment setType(…) (SurfaceHolder), SurfaceView, SurfaceHolder, and Surface setView(…) (AlertDialog.Builder), Setting a dialog’s contents shadow effect (adding), Layer List and Inset Drawables shape drawables, XML Drawables shared preferences, Simple persistence with shared preferences SharedPreferences, Simple persistence with shared preferences SharedPreferences.Editor, Simple persistence with shared preferences shouldOverrideUrlLoading(…) (WebViewClient), The Harder Way: WebView show() (Toast), Making toasts show(…) (DialogFragment), Showing a DialogFragment simulator (see emulator) SingleFragmentActivity, An abstract Activity class, Using an abstract class, Modifying SingleFragmentActivity singletons, Singletons and centralized data storage solutions file, Adding an Icon sp (scale-independent pixel), Screen pixel densities and dp and sp SQLite, Local Databases with SQLite SQLiteDatabase, Local Databases with SQLite, Working with Existing Runs SQLiteDatabase query(…) (SQLiteDatabase), Working with Existing Runs SQLiteOpenHelper, Storing Runs and Locations in a Database src directory, From Layout XML to View Objects stack traces in LogCat, Exceptions and Stack Traces CuuDuongThanCong.com logging of, Logging stack traces startActionMode(…) (Activity, Implementing contextual action mode in other views startActivity(…) (Activity), Starting an Activity startActivityForResult(…) (Activity), Getting a result back from a child activity startActivityForResult(…) (Fragment), Getting Results with Fragments startPreview() (Camera), SurfaceView, SurfaceHolder, and Surface startSearch(…) (Activity), Challenges state list (drawable), State List Drawables , Changing activated item backgrounds, State List Drawables status bar, hiding, Hiding the status bar and action bar stop() (MediaPlayer), Audio Playback stopPreview() (Camera), SurfaceView, SurfaceHolder, and Surface stretchable (drawable), Using 9-Patch Images string resources creating, Creating string resources defined, android:text referencing, Referencing resources in XML strings file default, Creating string resources defined, android:text strings.xml, Creating string resources styles, Cleaning Up with Styles, XML Drawables, State List Drawables defined, Styles, themes, and theme attributes inheritance, Challenge: Style Inheritance themes and, Styles, themes, and theme attributes styles.xml, Cleaning Up with Styles support library, Fragments and the support library SupportMapFragment, Showing the User’s Location on a Map @SuppressLint("HandlerLeak"), Using handlers @SuppressWarnings("deprecation"), SurfaceView, SurfaceHolder, and Surface @SuppressWarnings("unchecked"), Using handlers Surface client, SurfaceView, SurfaceHolder, and Surface defined, SurfaceView, SurfaceHolder, and Surface lifecycle of, SurfaceView, SurfaceHolder, and Surface SurfaceHolder interface setType(…), SurfaceView, SurfaceHolder, and Surface using, SurfaceView, SurfaceHolder, and Surface SurfaceHolder.Callback interface, SurfaceView, SurfaceHolder, and Surface SurfaceView defined, Camera I: Viewfinder getHolder(), SurfaceView, SurfaceHolder, and Surface SurfaceHolder and, SurfaceView, SurfaceHolder, and Surface -sw600dp suffix, Creating tablet alternatives system icons, Defining an options menu in XML CuuDuongThanCong.com T TableLayout, Defining the layout for HelloMoonFragment TableRow, Defining the layout for HelloMoonFragment tablets creating virtual devices for, Two-Pane Master-Detail Interfaces user interfaces for, Two-Pane Master-Detail Interfaces TAG constant, Making log messages target fragment, Setting a target fragment target SDK version, Honeycomb was big @TargetApi annotation, Suppressing Lint compatibility errors targetSdkVersion, Honeycomb was big, Target SDK version task manager, Using LogCat, Tasks and the Back Stack tasks and Back button, Tasks and the Back Stack defined, Tasks and the Back Stack v processes, For the More Curious: Processes vs Tasks temporal navigation, Enabling Ancestral Navigation TextView example, Laying Out the User Interface inheritance, Challenge: From Button to ImageButton setText(…), Using intent extras TextWatcher interface, Wiring widgets in a fragment themes, Styles, themes, and theme attributes, Manually resetting the app theme threads background (see background threads) main, You and Your Main Thread message queue, Communicating with the Main Thread processes and, For the More Curious: Processes vs Tasks as sequence of execution, You and Your Main Thread UI, You and Your Main Thread Toast, Making toasts toasts, Making toasts touch events handling, Handling Touch Events intercepting, Taking a Picture U UI fragments (see fragments) UI thread, You and Your Main Thread Up button, Enabling the app icon, Responding to the Up button Uri.Builder appendQueryParameter(…), Fetching XML From Flickr for escaping query strings, Fetching XML From Flickr CuuDuongThanCong.com URL for making URL from string, Networking Basics openConnection(), Networking Basics URLConnection, Networking Basics user interfaces defined by layout, App Basics for tablets, Two-Pane Master-Detail Interfaces laying out, Laying Out the User Interface styles for, Cleaning Up with Styles themes, Manually resetting the app theme uses-feature, Adding activity and camera permissions to the manifest uses-permission, Adding activity and camera permissions to the manifest uses-sdk, Honeycomb was big UUID.randomUUID(), Creating the Crime class V variable names conventions for, Generating getters and setters prefixes for, Generating getters and setters Variables view, Setting breakpoints versions (Android SDK) (see SDK versions) versions (firmware), Android SDK Versions video playback, Audio Playback Using MediaPlayer, For the More Curious: Playing Video VideoView, For the More Curious: Playing Video View (see also views, widgets) draw(), Rendering Inside onDraw(…) invalidate(), Tracking across motion events OnClickListener interface, Setting listeners onDraw(…), Rendering Inside onDraw(…) onRestoreStateInstance(…), Challenge: Rotations onSaveStateInstance(), Challenge: Rotations onTouchEvent(…), Handling Touch Events setOnTouchListener(…), Handling Touch Events subclasses, Laying Out the User Interface, Challenge: From Button to ImageButton view layer, Model-View-Controller and Android view objects, Model-View-Controller and Android ViewGroup, The view hierarchy, Creating a landscape layout ViewPager, Using ViewPager in support library, Standalone ID resources internals of, For the More Curious: How ViewPager Really Works OnPageChangeListener, Integrating CrimePagerActivity onPageScrolled(…), Integrating CrimePagerActivity onPageScrollStateChanged(…), Integrating CrimePagerActivity CuuDuongThanCong.com onPageSelected(…), Integrating CrimePagerActivity views (see also widgets, layouts) creating, Creating a Custom View custom, Creating a Custom View persisting, Challenge: Rotations simple v composite, Creating a Custom View touch events and, Handling Touch Events using fully-qualified name in layout, Creating BoxDrawingView virtual devices (see also emulator) creating, Running on the Emulator for tablets, Two-Pane Master-Detail Interfaces testing low-memory handling, For the More Curious: Testing onSaveInstanceState(Bundle) W web content browsing via implicit intent, The Easy Way: Implicit Intents displaying in browser, Browsing The Web & WebView displaying in WebView, Browsing The Web & WebView displaying within an activity, The Harder Way: WebView enabling JavaScript, The Harder Way: WebView web rendering events, responding to, The Harder Way: WebView WebChromeClient for enhancing appearance of WebView, Using WebChromeClient to spruce things up interface, Using WebChromeClient to spruce things up onProgressChanged(…), Using WebChromeClient to spruce things up onReceivedTitle(…), Using WebChromeClient to spruce things up WebSettings, The Harder Way: WebView WebView for presenting web content, The Harder Way: WebView handling rotation, Proper rotation with WebView WebViewClient, The Harder Way: WebView widgets attributes of, Laying Out the User Interface, Layout parameters Button, Laying Out the User Interface, Challenge: From Button to ImageButton CheckBox, Updating the Layout DatePicker, Setting a dialog’s contents defined, Laying Out the User Interface defining in XML, Laying Out the User Interface EditText, Defining CrimeFragment’s layout FrameLayout, Creating a landscape layout ImageButton, Challenge: From Button to ImageButton LinearLayout, Laying Out the User Interface, The view hierarchy CuuDuongThanCong.com padding, Margins vs padding references, Getting references to widgets ScrollView, Adding Buttons TableLayout, Defining the layout for HelloMoonFragment TableRow, Defining the layout for HelloMoonFragment TextView, Laying Out the User Interface in view hierarchy, The view hierarchy as view layer, Model-View-Controller and Android wiring in fragments, Wiring widgets in a fragment wiring up, Organizing imports wrap_content, android:layout_width and android:layout_height Writer, Creating the CriminalIntentJSONSerializer class X -xlarge suffix, Creating tablet alternatives XML Android namespace, The view hierarchy referencing resources in, Referencing resources in XML XML drawables (see drawables) XML parsing, Using XmlPullParser XmlPullParser, Using XmlPullParser CuuDuongThanCong.com More From Big Nerd Ranch Big Nerd Ranch exists to broaden the minds of our students and the businesses of our clients Whether we are training talented individuals or developing a company’s mobile strategy, our core philosophy is integral to everything we The Big Nerd Story The brainchild of CEO Aaron Hillegass, Big Nerd Ranch has hosted more than 2,000 students at the Ranch since its inception in 2001 Over the past ten years, we have had the opportunity to work with some of the biggest companies in the world such as Apple, Samsung, Nokia, Google, AOL, Los Alamos National Laboratory and Adobe, helping them realize their programming goals Our team of software engineers are among the brightest in the business and it shows in our work We have developed dozens of innovative and flexible solutions for our clients The Story Behind The Hat Back in 2001, Big Nerd Ranch founder, Aaron Hillegass, showed up at WWDC (World Wide Developers Conference) to promote the Big Nerd Ranch brand Without the money to buy an expensive booth, Aaron donned a ten-gallon cowboy hat to draw attention while passing out Big Nerd literature to prospective students and clients A week later, we landed our first big client and the cowboy hat has been synonymous with the Big Nerd brand ever since Already easily recognizable at 6'5, Aaron can be spotted wearing his cowboy hat at speaking engagements and conferences all over the world Training: Achieve Nerdvana Since 2001, Big Nerd Ranch has offered intensive programming courses taught by our expert instructors in a retreat environment It is at our Ranch where we think our students flourish Classes, accommodations, and dining all take place within the same building, freeing you to learn, code, and discuss with your programming peers and instructors At Big Nerd Ranch, we take care of the details; your only job is to learn Our Teachers Our teachers are leaders in their respective fields They offer deep understanding of the technologies they teach, as well as a broad spectrum of development experience, allowing them to address the concerns you encounter as a developer Big Nerd Ranch instructors provide the necessary combination of knowledge and outstanding teaching skills, enabling our students to leave the Ranch with a vastly improved set of skills The Big Nerd Way We have developed “The Big Nerd Ranch Way” This methodology guides the development and presentation of our classes The style is casual but focused, with brief lectures followed by hands-on exercises designed to give you immediate, relevant understanding of each piece of the technology you are learning For current information on particular classes and locations, visit CuuDuongThanCong.com www.bignerdranch.com/training On-site Training: Our Nerds, Your Location You can affordably and conveniently bring our classes to you Our expert instructors provide fresh and engaging, hands-on learning that will help your team advance Clients around the globe have praised our on-site instruction for its: Flexibility Classes can be booked when the timing is right for your team We can tailor our existing syllabi to meet your organization’s training needs Post-class mentorship is available to support your team on especially challenging projects Affordability No need for planes, trains, and automobiles for your staff; our Nerds come to you Train up to 22 students at a significant discount over open-enrollment training Nerd Know-how Our instructors are highly practiced in both teaching and programming They move beyond theory by bringing their real-life experiences to your team On-site training includes post-class access to our Nerds, our extensive Alumni Network, and our Big Nerd Ranch Forums Learning support doesn’t end just because your class does For your on-site training, we provide an instructor, all Big Nerd Ranch copyrighted class materials, gifts, certificates of completion and access to our extensive Alumni Network You provide the classroom set up, computers and related devices for all students, a projector and a screen To find out more about on-site, corporate training, visit www.bignerdranch.com/corporate Consulting: Achieve Nerdvana In-house & On-site When you contract with Big Nerd Ranch, we work directly with you to turn your needs into a fullfledged mobile and/or desktop solution Big Nerd Ranch holistically manages every client relationship Our goal is to communicate and educate our clients from project initiation to completion, while ultimately helping them gain a competitive advantage in their niche marketplace We take a detail-oriented approach to all of our project estimations Well work with you to define a strategy, specify product offerings and then build them into software that stands alone For more information about our consulting practice, visit www.bignerdranch.com/appdevelopment Books: The Big Nerd Ranch Guide Series CuuDuongThanCong.com At Big Nerd Ranch, our philosophy and our passion for education extends to our books Visit bignerdranch.com/books for Big Nerd Ranch guides currently available Contact Big Nerd Ranch Visit us online at www.bignerdranch.com/ Follow us on Twitter: @bignerdranch Email us at info@bignerdranch.com Give us a call at 404-478-9005 CuuDuongThanCong.com ... Android Build Process Android build tools Android and Model-View-Controller Creating a New Class Generating getters and setters Model-View-Controller and Android Benefits of MVC Updating the View... foundational content for several chapters Our co-instructors, Chris Stewart and Christopher Moore We thank them for their patience in teaching work-in-progress material, their suggestions and corrections... interface follows the “native look-and-feel” of your machine, so your screen may not look exactly like screenshots in this book Android Developer Tools a plug-in for Eclipse This book uses ADT