首页资源分类嵌入式系统安卓 > Android Studio Application Development

Android Studio Application Development

已有 450094个资源




    标    签:andorid

    分    享:


    andorid studio 应用指导


    Android Studio Application Development Create visually appealing applications using the new IntelliJ IDE Android Studio Belén Cruz Zapata BIRMINGHAM - MUMBAI Android Studio Application Development Copyright © 2013 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: October 2013 Production Reference: 1081013 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78328-527-3 www.packtpub.com Cover Image by Sheetal Aute (sheetala@packtpub.com) Credits Author Belén Cruz Zapata Reviewers Karan Kedar Balkar Angel Ivorra Pablo Pera Mira Antonio Hernández Niñirola Acquisition Editor Saleem Ahmed Commissioning Editors Shaon Basu Meeta Rajani Technical Editors Tanvi Bhatt Tarunveer Shetty Project Coordinator Amey Sawant Proofreader Jonathan Todd Indexer Priya Subramani Production Coordinator Adonia Jones Cover Work Adonia Jones About the Author Belén Cruz Zapata received her Engineer's degree in Computer Science from the University of Murcia in Spain, specializing in software technologies and intelligent and knowledge technologies. She earned an M.Sc in Computer Science and is now working in her Ph.D on the Software Engineering Research Group from the University of Murcia. Belén is based in Spain, although in the field of her Ph.D she is now collaborating with the Université Mohammed V-Soussi, in Rabat, as beneficiary of an Erasmus Mundus program. Her research is focused on the mobile world and cloud computing. She has a special interest in the development of mobile applications and new technologies. In the past few years, she has worked as a mobile developer for several platforms such as Android, iOS , and the Web. She maintains a blog at http://www.belencruz.com and you can follow her on Twitter: @belen_cz. I would like to thank Packt Publishing for offering me the opportunity to write this book. I would particularly like to thank Reshma Raman, Meeta Rajani, and Amey Sawant for their valuable help. I would also like to thank my mentors during the last months, Miguel R. and P. Salinas; my friends, especially Ana, Nerea, and the yupi group, for cheering me up; my family, especially my parents and brother, for supporting me; and finally my significant other for everything and more. About the Reviewers Karan Kedar Balkar has been working as an independent Android application developer for the past four years. Born and brought up in Mumbai, he holds a Bachelor's degree in Computer Engineering. He has written more than 50 programming tutorials on his personal blog (http://karanbalkar.com) covering popular technologies and frameworks. At present, he is working as a Software Engineer. He has been trained on various technologies including Java, Oracle, and .NET. Apart from being passionate about technology, he loves to write poems and travel to different places. He likes listening to music and enjoys playing the guitar. Firstly, I would like to thank my parents for their constant support and encouragement. I would also like to thank my friends, Srivatsan Iyer, Ajit Pillai, and Prasaanth Neelakandan for always inspiring and motivating me. I would like to express my deepest gratitude to Packt Publishing for giving me a chance to be a part of the reviewing process. Angel Ivorra is an autodidact software developer with 20 years of experience in several languages and platforms. He lives and works in Spain, in his own company (http://www.crestasoftware.es). I would like to thank my wife and daughter for all the patience during my long nights working. Pablo Pera Mira is an Android developer and entrepreneur. As a co-founder of Androidsx, Pablo has been involved in the design, development, marketing, and launch of more than 10 applications in the Google Play Store, with a total reach of over 10 million users. He currently works for Pixable, where he leads the development of the Android application Photofeed, a product from Pixable, based in New York. He previously worked as a backend Java engineer for the control platform of LHC, the particle accelerator in CERN, in Geneva. His first contact with real-world software was at Google, Zurich. Antonio Hernández Niñirola is a Computer Science Engineer and mobile applications developer, born and raised in Murcia in the southeast of Spain and currently living in Rabat, Morocco. He has developed several websites and also mobile applications that have been published in both the Google Play Market and the Apple Store. After his degree in Computer Science, he pursued a Master's degree in Teacher Training for Informatics and Technology. Antonio pushed his studies further and is now a doctorate student under the Software Engineering Group of the Faculty of Computer Science of the University of Murcia and is actually a researcher for the University Mohammed Soussi V in Rabat. As soon as Antonio got his first smartphone, a second-hand first generation iPhone, he started programming small applications as a form of entertainment. What started as a hobby, became a passion and is now leading his career both professionally and academically. www.PacktPub.com Support files, eBooks, discount offers, and more You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub. com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. TM http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. Why Subscribe? • Fully searchable across every book published by Packt • Copy and paste, print and bookmark content • On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access. Table of Contents Preface 1 Chapter 1: Installing and Configuring Android Studio 5 Preparing for installation 5 Downloading Android Studio 6 Installing Android Studio 6 Running Android Studio for the first time 6 Configuring the Android SDK 8 Summary 10 Chapter 2: Starting a Project 11 Creating a new project 11 Creating a custom launcher icon 13 Choosing your type of activity 13 Summary 15 Chapter 3: Navigating a Project 17 The project navigation panel 18 Project structure 19 Project settings 21 Summary 22 Chapter 4: Using the Code Editor 23 Editor settings 24 Code completion 26 Code generation 27 Navigating code 28 Useful actions 30 Summary 31 Table of Contents Chapter 5: Creating User Interfaces 33 The graphical editor 34 The text-based editor 35 Creating a new layout 36 Adding components 36 Supporting multiple screens 38 Changing the UI theme 41 Handling events 42 Summary 45 Chapter 6: Google Play Services 47 How Google Play Services work 47 Services available 48 Adding Google Play Services to Android Studio 49 Google Maps Android API v2 50 Google+ Platform for Android 52 Google Play In-app Billing v3 53 Google Cloud Messaging 54 Summary 54 Chapter 7: Tools 55 Software Development Kit Manager 55 Android Virtual Device Manager 57 Generating Javadoc 61 Version control system 62 Summary 64 Chapter 8: Debugging 65 Running and debugging 65 LogCat 68 DDMS 69 Threads 70 Method profiling 71 Heap 72 Allocation tracker 73 Network statistics 73 File Explorer 74 Emulator control 74 System information 74 Summary 75 [ ii ] Chapter 9: Preparing for Release What is an APK file Previous steps Generating a signed APK Summary Chapter 10: Getting Help Getting help from Android Studio Android online documentation Updates Summary Index Table of Contents 77 77 79 80 81 83 83 84 86 87 89 [ iii ] Preface Mobile applications have had a huge increase in popularity in the last few years and this interest is still growing among users. Mobile operating systems are available not only for smartphones but tablets as well, therefore increasing the possible market quota for these applications. Android has characteristics that make it pleasant to developers such as open source and a certain level of community-driven development. Android has always been contesting with iOS (the Apple mobile system) in everything and with XCode, iOS presented itself as a more centralized development environment. The new IDE Android Studio makes this centralization finally available for Android developers and makes this tool indispensable for a good Android developer. This book about Android Studio shows users how to develop and build Android applications with this new IDE. It is not only a getting started book but also a guide to advanced developers to build their applications faster and more productively. This book will follow a tutorial approach from the basic features to the steps to build for release, including practical examples. What this book covers Chapter 1, Installing and Configuring Android Studio, describes the installation and basic configuration of Android Studio. Chapter 2, Starting a Project, shows how to create a new project and the type of activities we can select. Chapter 3, Navigating a Project, explores the basic structure of a project in Android Studio. Chapter 4, Using the Code Editor, exposes the basic features of the code editor in order to get the best out of it. Preface Chapter 5, Creating User Interfaces, focuses on the creation of the user interfaces using both the graphical view and the text-based view. Chapter 6, Google Play Services, introduces the current existing Google Play Services and how to integrate them into a project in Android Studio. Chapter 7, Tools, exposes some additional tools such as the Android SDK tools, Javadoc, and the version control integration. Chapter 8, Debugging, shows in detail how to debug an application in Android Studio and the provided information when debugging. Chapter 9, Preparing for Release, describes how to prepare your application for release. Chapter 10, Getting Help, introduces how to get help using Android Studio and provides a list of online sites to learn more about the topics seen in this book. What you need for this book For this book you need a computer with a Windows, Mac OS, or Linux system. You will also need to have Java installed in your system. Who this book is for This book is not only a getting started book but also a guide to advanced developers who have not used Android Studio to build their Android apps before. This book is great for developers who want to learn the key features of Android Studio and for developers who want to create their first app. It's assumed that you are familiar with the object-oriented programming paradigm and the Java programming language. It is also recommended you understand the main characteristics of the Android mobile system. Conventions In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: "We will go through the most important folders in our project, build, gen, libs, and the folders under src/main. " [2] Preface A block of code is set as follows: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: setContentView(R.layout.activity_main); if (savedInstanceState != null) { System.out.println("savedInstanceState = [" + savedInstanceState + "]"); } New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "In the Android Studio welcome screen, navigate to Configure | Project Defaults | Project Structure." Warnings or important notes appear in a box like this. Tips and tricks appear like this. Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to feedback@packtpub.com, and mention the book title via the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors. [3] Preface Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub. com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support. Piracy Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at copyright@packtpub.com with a link to the suspected pirated material. We appreciate your help in protecting our authors, and our ability to bring you valuable content. Questions You can contact us at questions@packtpub.com if you are having a problem with any aspect of the book, and we will do our best to address it. [4] Installing and Configuring Android Studio You want to get familiar with the new and official Google IDE Android Studio. You want to know the features available in this environment. You would like to make your own Android applications, and you want these applications to be available to other users on Google Play Store. Can you do this easily? How can you achieve this? This chapter will show you how to prepare your new Android Studio installation and how to take your first steps in the new environment. We'll begin by preparing the system for the installation and downloading the required files. We'll see the welcome screen that prompts when running Android Studio for the first time and we'll configure the Android SDK (Software Development Kit) properly so you have everything ready to create your first application. These are the topics we'll be covering in this chapter: • Installation of Android Studio • Welcome screen when running Android Studio for the first time • Configuration of the Android SDK Preparing for installation A prerequisite to start working with Android Studio is to have Java installed in your system. The system also must be able to find the Java installation. This can be achieved by setting an environment variable named JAVA_HOME, which must point to the JDK (Java Development Kit) folder in your system. Check this environment variable to avoid future issues during the installation of Android Studio. Installing and Configuring Android Studio Downloading Android Studio The Android Studio package can be downloaded from the Android developer tools web page at: http://developer.android.com/sdk/installing/studio.html. This package is an EXE file for Windows systems: http://dl.google.com/android/studio/android-studio-bundle-130.737825windows.exe. A DMG file for Mac OS X systems: http://dl.google.com/android/studio/android-studio-bundle-130.737825mac.dmg. Or a TGZ file for Linux systems: http://dl.google.com/android/studio/android-studio-bundle-130.737825linux.tgz. Installing Android Studio In Windows, launch the EXE file. The default installation directory is \Users\\Appdata\Local\Android\android-studio. The Appdata directory is usually a hidden directory. In Mac OS X, open the DMG file and drop Android Studio into your applications folder. The default installation directory is /Applications/Android/ Studio.app. In Linux systems, unpack the TGZ file and execute the studio.sh script located at the android-studio/bin/ directory. If you have any problem in the installation process or in the following steps, you can get help about it and the known issues by checking Chapter 10, Getting Help. Running Android Studio for the first time Execute Android Studio and wait until it loads completely (it may take a few minutes). The first time executing Android Studio, a welcome screen will be prompted. As shown in the following screenshot, the welcome screen includes a section to open recent projects and a section of Quick Start. We can create a new project, import a project, open a project, or even perform more advanced actions such as checking out from a version control system or opening the configuration options. [6] Chapter 1 Let's have a look at the various options available in the Quick Start section: • New Project...: Creates a new Android project • Import Project: Creates a new project by importing existing sources from your system • Open Project: Opens an existing project • Check out from Version Control: Creates a new project by importing existing sources from a version control system • Configure: Opens the configuration menu °° Settings: Opens Android Studio settings °° Plugins: Opens the plugins manager for Android Studio °° Import Settings: Imports the settings from a file (.jar) °° Export Settings: Exports the settings to a file (.jar) °° Project Defaults: Opens the project defaults settings menu °° Settings: Opens the template project settings. These settings are also reachable from the Android Studio settings (Configure | Settings) °° Project Structure: Opens the project and platform settings °° Run Configurations: Opens the run and debug settings [7] Installing and Configuring Android Studio • Docs and How-Tos: Opens the help menu °° Read Help: Opens the Android Studio help, online version °° Tips of the Day: Opens a dialog with the tip of the day °° Default Keymap Reference: Opens an online PDF containing the default keymap °° JetBrains TV: Opens a JetBrains website containing video tutorials °° Plugin Development: Opens a JetBrains website containing information for plugin developers Configuring the Android SDK The essential feature that has to be correctly configured is the Android SDK. Although Android Studio automatically installs the last Android SDK available, so you should already have everything you need to create your first application, it is important to check it and to learn how we can change it. In the Android Studio welcome screen, navigate to Configure | Project Defaults | Project Structure. In Platform Settings, click on SDKs. The list of the installed SDKs will be shown and you should have at least one Android SDK in the list. In Project Settings, click on Project to open the general settings for the project default template. You should have a selected Project SDK as shown in the next screenshot. This selected SDK is the default that will be used in our Android projects, but even so we can change it later for specific projects that require special settings. [8] Chapter 1 If you do not have any Android SDK configured in Android Studio, then we have to add it manually. To accomplish this task, in Platform Settings | SDKs click on the green plus button to add an Android SDK to the list and then select the home directory for the SDK. Check if you have it in your system by navigating to your Android Studio installation directory. You should find a folder named sdk that contains the Android SDK and its tools. The Android Studio installation directory may be in a hidden folder, so click on the button highlighted in the following screenshot to Show Hidden Files and Directories: If you want to use another Android SDK different from the one included in Android Studio, select it instead. For example, if you previously used the ADT (Android Development Tools) plugin for Eclipse, you already have an Android SDK installation in your system. You could also add both of them. When you finish adding the SDK, it will appear in the list and you can select the default from the project settings. Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub. com/support and register to have the files e-mailed directly to you. [9] Installing and Configuring Android Studio Summary We have successfully prepared the system for Android Studio and installed our Android Studio instance. We ran the Studio for the first time and now we know the options available in the welcome screen. We have also learned how to configure our Android SDK and how to install it manually in case you want to use a different version. Fulfilling these tasks will leave your system with Android Studio running and configured to create your first project. In the next chapter, we will learn about the concept of project and how it includes everything the application requires, from classes to libraries. We will create our first project and we will discuss the different kinds of activities available in the wizard. [ 10 ] Starting a Project You just installed Android Studio and now you want to get familiar with its features. You want to understand the necessary fields when creating a project. You would like to know how to add an icon to your application and associate it on the project, and you are wondering how to create the main activity and which type of activity to choose. How can you achieve this using Android Studio? The goal of this chapter is to create a new project with the basic content it should start out with. We will use the Android Studio wizard to create the project and we will go through the project configuration fields. We will choose a launch icon for our application and we will go through the different kinds of activities available in the wizard to pick as the main activity for our project. These are the topics we'll be covering in this chapter: • Creating a new project • Creating your application icon • Types of activities to choose as your main activity Creating a new project To create a new project, click on the New Project option from the welcome screen. If you are not in the welcome screen, then navigate to File | New Project. The new project wizard opens. Starting a Project The first step of the wizard is enough to create a project, but if you check the Create custom launcher icon option, a second step is added to the wizard, and if you check the Create activity option, two additional steps are added. Check both of them. The fields that will be shown on the new project wizard are as follows: • Application name: It is the name shown in Google Play and the one that users see. • Module name: It is the name used only by Android Studio. • Package name: Unique identifier of your application usually in the form com.company_name.app_name or reverse_company_domain.app_name. This form reduces the risk of name conflicts with other applications. • Project location: It is the directory to save the project in your system. • Minimum required SDK: It is the minimum SDK supported by your application. Devices with a previous SDK will not be able to install your application. Try to reach a balance between supported devices and available features. If your application does not require a specific feature published in the newest SDKs, then you can select an older API (Application Programming Interface). The last dashboards published by Google about the platforms distribution show that 95.5 percent of the devices use Android 2.3 or superior. If you select Android 2.2, then the percentage rises to 98.5 percent. Official Android dashboards are available at http://developer. android.com/about/dashboards/index.html. • Target SDK: It is the highest SDK that you have tested against your application. You should keep this value updated to the latest versions. • Compile with: It is the SDK used to compile your application. This SDK is one of the SDKs you have installed and configured in Android Studio. • Theme: Selects a default user interface theme for your application. [ 12 ] Chapter 2 The option Mark this project as a library is used to create the project as a library module. A library can be referenced in other projects to share its functionality. Do not check this option. Consider the fields shown in the previous screenshot. Select API 10 as the minimum SDK and API 17 as the target SDK. In the Compile with field, select the highest API version you have installed (API 17). Click Next. Creating a custom launcher icon This step allows you to create your application icon and will be shown if you checked the Create custom launcher icon option in the first step. Android projects store several images resolutions to choose the most appropriate to the device screen resolution when the application is executing. To ensure that the icon will be displayed properly in every device, check if the XXHDPI image is not pixelated. There are three options to create your application icon, an image, one of the provided cliparts, or a text. The most common is an image. You can select your own image file to create the icon and adjust some parameters such as its padding, its shape, or the background color. Choose the Image option and leave the default image and options as they are. Click on Next. Choosing your type of activity This step allows you to create the main activity of your application. This step will be shown if in the first one you checked the Create activity option. [ 13 ] Starting a Project Several types of activities can be selected: • Blank Activity: This creates a blank activity with an action bar. The action bar includes a title and an options menu. The navigation type can be a tabbed user interface (tabs fixed or scrollable), horizontal swipe, or a drop-down menu. See more about action bars at http://developer.android.com/ guide/topics/ui/actionbar.html. • Fullscreen Activity: This template hides the system user interface (such as the notification bar) in a full-screen view. The full-screen mode is alternated with an action bar that shows up when the user touches the device screen. • Login activity: This template creates its view as a login screen allowing the users to log in or register with an e-mail and password. [ 14 ] Chapter 2 • Master/Detail Flow: This template splits the screen into two sections: a left menu and the detail of the selected item on the right. On a smaller screen, just one section is displayed, but on a bigger screen, both sections are displayed at the same time. • Settings Activity: This creates a preference activity with a list of settings. Select the Blank Activity and click on Next. In the last step, we can give a name to the activity and its associated layout. Leave the default values, select no navigation type, and click Finish. Summary We have used the Android Studio wizard to create our first project and we filled the configuration fields. We chose the launch icon for our application and made sure that it's going to display properly with any resolution. We went through the different kinds of activities. In the next chapter, we will go through the different elements of the structure of Android Studio. We will find where we can create new classes, add and access libraries, and how to configure the project. [ 15 ] Navigating a Project You just created your first Android Studio project and now you want to understand what is going on. You want to start programming, but before this you need to get familiar with the navigation of the project. How is everything structured? What settings can you change on the project? How can you change these settings and what do they mean? This chapter is designed to introduce the structure of a project in Android Studio. We will start by understanding the project navigation panel. We will go through the most important folders in our project, build, gen, libs, and the folders under src/main, and we will learn how to change the project settings. These are the topics we'll be covering in this chapter: • Navigation panel • Project structure • Changing project properties Navigating a Project The project navigation panel Initially in the main view of Android Studio, no project or file is displayed as you can see in the next screenshot. As Android Studio suggests, press Alt + 1 to open the project view. You can also open it by clicking on the Project button from the left edge. The project view shows the list of the open projects. The projects are displayed using a hierarchical view. In the upper-left corner of the project explorer we can change the type of view: Project or Packages. The first one shows the directory structure of the project, while the second one shows only the package structure. [ 18 ] Chapter 3 In the upper-right corner there are some actions and a drop-down menu to configure the project view. These actions are highlighted in the following screenshot: Click on the project name with the right mouse button to open the context menu, or click on any element of the project. From this menu we can: • Create and add new elements to the project • Cut, copy, paste, or rename files in the project • Find elements in the project • Analyze and reformat the code • Build the project • Compare files • Open files in Explorer Project structure In the project navigation pane, we can examine the project structure. Inside the project structure is a folder with the name of our application. This folder contains the application structure and files. The most important elements of the application structure are: • build/: A folder that contains the compiled resources after building the application and the classes generated by the Android tools such as the R.java file, which contains the references to the application resources. • libs/: A folder that contains the libraries referenced from our code. [ 19 ] Navigating a Project • src/main/: A folder that contains the sources of your application. All the files you will usually work with are in this folder. The main folder is subdivided as follows: °° java/: A folder that contains the Java classes organized as packages. Every class we create will be in our project package namespace (com. example.myapplication). When we created our first project, we also created its main activity, so the activity class should be in this package. The next screenshot shows this main activity class inside the project structure: °° res/: A folder that contains project resources such as the XML files that specify layouts and menus or the images files. °° drawable/: A folder that contains the images used in our application. There are different drawable folders categorized into the different screen densities. When we created our first project, we also created our application icon, so this icon is already in these folders named as ic_launcher.png. °° layout/: A folder that contains the XML definitions of the views and their elements. °° menu/: A folder that contains the XML definitions of the menus of the application. °° values/: A folder that contains the XML files that define sets of name-value pairs. These values can be colors, strings, or styles. There are different values folders categorized into different screens options to adapt the interface to them. For example, to enlarge the components or the fonts when the application is running on a tablet. [ 20 ] Chapter 3 °° AndroidManifest.xml: This file is essential in an Android project and is generated automatically when we create the project. This file declares basic information needed by the Android system to run the application, package name, version, activities, permissions, intents, or required hardware. • build.gradle: This file is the script used to build our application. Project settings There are two dialog boxes that contain project settings: File | Settings menu and File | Project Structure. Both are also available in the toolbar. Select your project from the project view and navigate to File | Settings menu. In the left menu of the settings dialog, there is a section named Project Settings [MyApplication]. Some important options are: • Code Style: Configures the default code style scheme. • Compiler: Configures the Android DX compiler used when building our application. • File Encodings: Changes the file's encoding. The default encoding is UTF-8. • Gradle: It gives the Gradle's configuration. Gradle is a tool similar to Apache Ant and Apache Maven, based on Groovy to build and manage Java projects. Gradle is integrated in Android Studio. • Language Injections: Adds or removes the available languages used in the editor. • Maven: It gives the Maven configuration. Maven is a tool similar to Apache Ant and Gradle, based on XML to build and manage Java projects. Maven is integrated in Android Studio. • Version Control: Configures the version control options. Version control will be explained in more detail in Chapter 7, Tools. [ 21 ] Navigating a Project In addition to these settings, there are more of them in the project structure dialog. Navigate to File | Project Structure menu. The Project Settings are: • Project: We can change the project name and the project SDK. Remember in Chapter 1, Installing and Configuring Android Studio, when we selected a SDK as the default one. In this screen we can change this SDK just for the current project. • Modules: This screen shows a list of the existing modules with its facets. We can also remove them or create new ones. According to IntelliJ IDEA (http://www.jetbrains.com/idea/webhelp/module.html), A module is a discrete unit of functionality which you can compile, run, test and debug independently. • Libraries: This screen shows a list of the libraries imported into the project. We can also remove them or add new ones. They will be added to the libs/ folder. • Facets: This screen shows a list of the existing facets. We can also remove them or create new ones. These facets were also displayed in the Modules view. According to IntelliJ IDEA (http://www.jetbrains.com/idea/ webhelp/facet.html), Facets represent various frameworks, technologies and languages used in a module. They let IntelliJ IDEA know how to treat the module contents and thus ensure conformity with the corresponding frameworks and technologies. Summary We have learned how the projects are presented in Android Studio and what folders are in it by default once it is created. Now we understand the reasons for each folder and what AndroidManifest.xml is for. We went through the project settings both in the File | Settings and the File | Project Structure dialogs. By now, you should know how to manipulate and navigate a project in Android Studio. In the next chapter we will learn how to use the text editor. A proper knowledge of the text editor is important in order to improve our programming efficiency. We will learn about the editor settings and how to auto-complete code, use pre-generated blocks of code, and navigating the code. We will also learn about some useful shortcuts. [ 22 ] Using the Code Editor You have created your first project and you know how to navigate through the different folders, subfolders, and files. It's time to start programming! Have you ever wanted to be able to program more efficiently? How can you speed up your development process? Do you want to learn useful shortcuts to, for example, comment more than one line at once, find and replace strings, or move faster through different parameters in a method call? In this chapter we will learn how to use the code editor and how to customize it in order to feel more comfortable when programming. It is worth knowing the basic features of the code editor in order to increase the developer productivity. We will learn about code completion and code generation. Finally, we will learn some useful shortcuts and hotkeys to speed up our development process. These are the topics we'll be covering in this chapter: • Customizing the code editor • Code completion • Code generation • Find related content • Useful shortcuts Using the Code Editor Editor settings To open the editor settings navigate to File | Settings, section IDE Settings, menu Editor. This screen displays the general settings of the editor. We recommend checking two options that are unchecked by default: • Change font size (Zoom) with Ctrl + Mouse Wheel: This option allows us to change the font size of the editor using the mouse wheel, as we do in other programs such as web browsers. • Show quick doc on mouse move: If we check this option, when we move the mouse over a piece of code and wait 500 ms, a quick doc about that code will be displayed in a small dialog. When we move the mouse again, the dialog automatically disappears, but if we move the mouse into the dialog, then we can examine the doc in detail. This is very useful, for example, to read what a method does and its parameters without navigating to it. There are more settings distributed among seven categories: • Smart Keys: Configures actions to be done automatically when typing, such as adding closing brackets, quotes or tags; or indenting the line when we press the Enter key. • Appearance: Configures the appearance of the editor. We recommend checking the next two options that are unchecked by default: °° Show line numbers: Shows the line numbers in the left edge of the editor. It can be very useful when we are debugging or examining the log. [ 24 ] Chapter 4 °° Show method separators: Visually separates the methods of a class. • Colors & Fonts: Changes the fonts and colors. There are a lot of options and elements to configure (keywords, numbers, warnings, errors, comments, strings, and so on). We can save the configurations as schemes. • Editor Tabs: Configuration of the editor tabs. We suggest you select the Mark modified tabs with asterisk option to easily detect the modified and not-saved files. • Code Folding: The code folding option allows us to collapse or expand code blocks. It is very useful to hide code blocks that we are not editing, simplifying the code view. We can collapse or expand the blocks using the icons from the editor or using the Code | Folding menu. • Code completion: Configures the code completion options. Code completion is examined in detail in the next section. • Auto Import: Configures how the editor behaves when we paste code that uses classes that are not imported in the current class. By default when we do this, a pop up appears to add the import command. If we check the option Add unambiguous imports on the fly, the import command will be added automatically without our interaction. [ 25 ] Using the Code Editor Code completion Code completion helps us to write code quickly by suggestion lists and automatically completing the code. The basic code completion is the list of suggestions that appears while we are typing. If the list is not displayed, press Ctrl + the Spacebar to open it. Keep typing, select a command from the list, and press Enter or double-click to add it in your code. If the code we are writing is an expression, but we want to insert the expression in its negated form, when we select the expression from the suggestion list, instead of pressing Enter or double-clicking on it, press the exclamation mark key (!). The expression will be added with negation. Another type of code completion is the smart type code completion. If we are typing a command to call a method with a String parameter, then just the String objects will be suggested. This smart completion occurs in the right part of an assignment statement, parameters of a method call, return statements or variable initializers. To open the smart suggestions list, press Ctrl + Shift + the Spacebar. To show the difference between these two types of suggestion lists, create in your code two objects of different classes, String and int. Then call to a method with a String parameter, for example, the method i of the Log class. When typing the String parameter, note the difference between opening the basic suggestion list (Ctrl + the spacebar) as the next screenshot shows, and opening the smart type suggestion list (Ctrl + Shift + the Spacebar) as the screenshot on the next page shows. [ 26 ] Chapter 4 In the first list, which is shown in the previous screenshot, both objects are suggested although the int object does not match the parameter class. In the second one, which is shown in the following screenshot, just String objects are suggested. One last utility of code completion is the completion of statements. Type a statement, press Ctrl + Shift + Enter, and notice how the closing punctuation is automatically added. If you press those keys after typing the keyword if, the parenthesis and the brackets are added to complete the conditional statement. This shortcut can also be used to complete methods declarations. Start typing a method and after typing the opening parenthesis, or after typing the method parameters, press Ctrl + Shift + Enter. The closing parenthesis and the brackets are added to complete the method specification. Code generation To generate blocks of code in a class, navigate to Code | Generate or press the shortcut Alt + Insert. We can generate constructors, getters, and setters methods, equals and toString methods, override or delegate methods. Another way to generate code is surrounding some of our code with some statements (if, if/else, while, for, try/catch, and so on). Select a code line and navigate to Code | Surround With or press Ctrl + Alt + T. [ 27 ] Using the Code Editor The third option is inserting code templates. Navigate to Code | Insert Live Templates to open a dialog box of the available templates. These templates can insert code to iterate collections, arrays, lists, and so on; code to print formatted strings, code to throw exceptions, or code to add static and final variables. In the left edge of the dialog, each template has a prefix, so if you type the prefix in the editor and press the Tab key, the code template is added automatically. Try to type inn at the end of the onCreate method of our main activity and press Tab. A conditional block will appear. In this new block, type soutm and press Tab again. The result is shown next. protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState != null) { System.out.println("savedInstanceState = [" + savedInstanceState + "]"); } } Navigating code The most direct way to navigate to declarations or type declarations is to press Ctrl and click on the symbol when it is displayed as a link. This option is also accessible from Navigate | Declaration. From the left edge of the editor we can navigate through the hierarchy of methods. Next to the method declarations that belong to a hierarchy of methods, there is an icon that indicates if a method is implementing an interface method, implementing an abstract class method, overriding a superclass method, or on the contrary, if a method is implemented or is overridden by other descendants. Click on these icons to navigate to the methods in the hierarchy. This option is also available via Navigate | Super Method or Navigate | Implementation(s). Test it by opening the main activity of our first project (MainActivity.java). [ 28 ] Chapter 4 Another useful utility related to code navigation is the use of custom regions. A custom region is just a piece of code that you want to group and give a name to. For example, if there is a class with a lot of methods, we can create some custom regions to distribute the methods among them. A region has a name or description and it can be collapsed or expanded using code folding. To create a custom region we can use the code generation. Select the fragment of code, navigate to Code | Surround With, and select one of these two options: • Comments • region…endregion Comments Both of them create a region but using a different style. When we are using custom regions, we can navigate them using the Navigate | Custom Region menu. The rest of the navigation options are accessible from the menu Navigate: • Class/File/Symbol: Finds a class, a file, or a symbol by its name. • Line: Goes to a line code by its number. • Last Edit Location: Navigates to the most recent change point. • Test: Navigates to the test of the current class. [ 29 ] Using the Code Editor • File Structure: Opens a dialog box that shows the file structure. Open the file structure of our main activity and observe how the structure is presented, displaying the list of methods, the icons that indicate the type of element, or the icons that indicate the visibility of the element. • File Path: Opens a dialog that shows the complete path to the file opened in the editor. • Type Hierarchy: Opens a dialog that shows the type hierarchy of the selected object. • Method Hierarchy: Opens a dialog that shows the method hierarchy of the selected method. • Call Hierarchy: Opens a dialog that shows the call hierarchy of the selected method. • Next Highlighted Error: Navigates to the next error. • Previous Highlighted Error: Navigates to the previous error. • Next Method: Navigates to the next method. • Previous Method: Navigates to the previous method. Useful actions Some useful shortcuts are exposed in the following list: • Ctrl + W: Selects the expressions based on grammar. Keep pressing these keys again and again to expand the selection. The opposite command is Ctrl + Shift + W. • Ctrl + /: Comments each line of the selected code. To use block comments press Ctrl + Shift + /. • Ctrl + Alt + I: Indents the selected code. Useful when you finish writing a block of code or method to clean it up. [ 30 ] Chapter 4 • Ctrl + Alt + O: Optimizes the imports, removing the unused ones and reordering the rest of them. • Shift + Ctrl + Arrows: Moves the selected code to another line. • Alt + Arrows: Switches between the opened tabs of the editor. • Ctrl + F: Finds a string in the active tab of the editor. • Ctrl + R: Replaces a string in the active tab of the editor. • Ctrl + A: Selects all the code of the opened file. • Ctrl + D: Copies the selected code and pastes it at the end of it. If no code is selected, then the entire line is copied and pasted in a new line. • Ctrl + Y: Removes the entire line without leaving any blank line. • Ctrl + Shift + U: Toggles case. • Tab: Moves to the next parameter. Summary By the end of this chapter, the user should learn some useful tricks and useful actions to make the most of the code editor. We know now how to use code completion, code generation, and some useful shortcuts for speeding up different actions. We have also customized our code editor and we are now ready to start programming. In the next chapter, we will start creating our first user interface using layouts. We will learn how to create a layout using the graphical wizard and how to create it editing the XML layout file using the text-based view. We will create our first application, a classic Hello World example using the text view component. We will also learn about how to prepare our application for multiple screen sizes and adapt them for different device orientations. Finally, we will learn about UI themes and how to handle events. [ 31 ] Creating User Interfaces Now that you have created your first project and have become familiar with the code editor and its functionalities, we will begin our application by creating our user interface. Is there more than one way to create a user interface using Android Studio? How can you add components to your user interface? Have you ever wondered how to make your applications support different screen sizes and resolutions? This chapter focuses on the creation of the user interfaces using layouts. The layouts can be created using a graphical view or a text-based view. We will learn how to use both of them to create our layout. We will also code a Hello World application using simple components. We will learn about fragmentation on different Android-based devices and how to prepare our application for this issue. We will end this chapter with basic notions of handling events on our application. These are the topics we'll be covering in this chapter: • Existing layout editors • Creating a new layout • Adding components • Supporting different screens • Changing the UI theme • Handling events Creating User Interfaces The graphical editor Open the main layout located at /src/main/res/layout/activity_main.xml in our project. The graphical editor will be opened by default. Initially, this main layout contains just a text view with a Hello world! message. To switch between the graphical and the text editor, click on the bottom tabs, Design and Text. The toolbar contains some options to change the layout style and preview. The options of the toolbar are explained throughout the chapter. The components tree displays the components placed in the layout as a hierarchy. The properties inspector shows the properties of the selected component from the layout and it allows us to change them. [ 34 ] Chapter 5 The palette lists the existing UI (User Interface) components to place in our layout. The palette organizes the components in different categories. • Layouts: A layout is a container object to distribute the components on the screen. The root element of a user interface is a layout object, but layouts can also contain more layouts, creating a hierarchy of components structured in layouts. The recommendation is to keep this layout hierarchy as simple as possible. Our main layout has a relative layout as a root element. • Widgets: Buttons, checkboxes, text views, switches, image views, progress bars, spinners, or web views are in this category. They are the most common components used in most layouts. • Text Fields: These are inputs in which users can type text. The difference between them is the type of text users can type. • Containers: These are containers group components that share a common behavior. Radio groups, list views, scroll views, or tab hosts are some of them. • Date & Time: These are components related to date and time, as a calendar or clocks. • Expert: These components are not as common as the ones in the widgets category, but it is worth taking a look at them. • Custom: These are components that allow us to include our custom components, which are usually other layouts from our project. The text-based editor Change the graphical editor to the text editor by clicking on the Text tab. [ 35 ] Creating User Interfaces The toolbar is the same as the graphical editor. The preview displays the layout but it cannot be changed, you should use the design tab instead. The components are added to the layout using their XML declarations. The properties are also configured using the XML declarations. Like the graphical editor, the text editor shows just the text view element inside the root layout. Creating a new layout When we created our main activity, the associated layout was also created. This is a way to create a layout, while creating an activity. If we want to add an independent layout without creating a new activity, then click with the right mouse button on the layouts folder (res/layout/) and navigate to New | Layout resource file. You can also navigate to the menu option File | New | Layout resource file. Type the filename and the root element. Once the layout is created, the associated activity can be changed from the editor to another one. If the layout has no activity, any existing one can be linked to it from the editor. To accomplish this, in the toolbar of the layout editor, search for the activity option, click on it, and select the Associate with other Activity option. A dialog box that lists all the activities of your project will be opened so you can select one of them. Adding components Our main layout is a relative layout and contains a text view saying Hello world!, but let's add a new component. The easiest way to do this is using the graphical editor, so open the design tab. Select a component and drag it into the layout preview, for example, navigate to Text Fields | Person Name and place it below the text view. In the component tree view, now there is a new EditText object. Keep the text field selected to examine its properties loaded in the properties inspector. Let's change some of them and observe the differences in the layout preview and in the component tree. 1. layout:width: Its current value is wrap_content. This option will adapt the width of the field to its content. Change it to match_parent to adapt it to the parent layout width (the root relative layout). 2. hint: Type Enter your name as the hint of the field. The hint is a text shown when the field is empty to indicate the information that should be typed. Due to the field having a default value, Name, the hint is not visible. [ 36 ] Chapter 5 3. id: Its current ID is @+id/editText. This ID will be used from the code to get access to this object and is the one displayed in the component tree. Change it to @+id/editText_name to easily distinguish it from other text fields. Check that in the component tree the component ID has also changed. 4. text: Delete the value of this field. The hint should now be visible. If we switch to the text editor, we can see the XML definition of the text field with the properties we edited: From the text editor, the existing components and their properties can also be changed. Modify the text view ID (android:id property) from @+id/textView to @+id/textView_greeting. Having a descriptive ID is important since it will be used from our code. Descriptive variable names allow the code to be self-documenting. [ 37 ] Creating User Interfaces Let's add another component using the text editor this time. Press the open tag key and start typing Button. Let the suggestion list appear and select a Button object. Inside the Button tag, add the next properties:

    EEWORLD下载中心所有资源均来自网友分享,如有侵权,请发送举报邮件到客服邮箱bbs_service@eeworld.com.cn 或通过站内短信息或QQ:273568022联系管理员 高进,我们会尽快处理。