37,19 €
Master the art of creating impressive and reactive UIs for mobile applications on the latest version of Android Oreo.
This book is for novice Android and Java developers who have a basic knowledge of Android development and want to start developing stunning user interfaces.
A great user interface (UI) can spell the difference between success and failure for any new application. This book will show you not just how to code great UIs, but how to design them as well. It will take novice Android developers on a journey, showing them how to leverage the Android platform to produce stunning Android applications.
Begin with the basics of creating Android applications and then move on to topics such as screen and layout design. Next, learn about techniques that will help improve performance for your application. Also, explore how to create reactive applications that are fast, animated, and guide the user toward their goals with minimal distraction.
Understand Android architecture components and learn how to build your application to automatically respond to changes made by the user. Great platforms are not always enough, so this book also focuses on creating custom components, layout managers, and 2D graphics. Also, explore many tips and best practices to ease your UI development process.
By the end, you'll be able to design and build not only amazing UIs, but also systems that provide the best possible user experience.
This book takes an easy tutorial approach to help you learn how to create consistent and efficient user interfaces for your apps. The book first takes you through the basics of user interfaces such as basic layouts, inputs, and controls, and also covers animations and graphics. By the end of the book, you will have learned best practices and will be able to develop inspired interfaces that look good and also work subtly in the background.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 379
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 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: November 2017
Production reference: 1161117
ISBN 978-1-78847-505-1
www.packtpub.com
Author
Jason Morris
Copy Editor
Shaila Kusanale
Reviewers
Jessica Thornsby Michael Duivestein
Project Coordinator
Devanshi Doshi
Commissioning Editor
Kunal Chaudhari
Proofreader
Safis Editing
Acquisition Editor
Noyonika Das
Indexer
Francy Puthiry
Content Development Editor
Onkar Wani
Graphics
Jason Monteiro
Technical Editor
Sachin Sunilkumar
Production Coordinator
Arvindkumar Gupta
Jason Morris is a multi-discipline software developer. He has been developing software for as long as he can remember. He's written software for the desktop, server, feature phones and smartphones, and the web and microcontrollers. Jason programs in a wide range of programming languages, and loves a new programming challenge. When he's not writing code or spending time with his family, taking photos or camping, he's probably thinking about programming. In 2010/2011, he wrote Android User Interface Development: A Beginner's Guide, which helped many beginner Android developers take their first steps into the realm of User Interface design and development for mobile devices.
Jessica Thornsby studied poetry, prose, and scriptwriting at Bolton University before discovering the world of open source and technical writing, and has never looked back since. Today, she is a freelance technical writer and full-time Android enthusiast, the author of Android UI Design, and the coauthor of iWork: The Missing Manual.
Michael Duivestein is a software engineer living in Cape Town, South Africa. His curiosity about all things code has meant he has enjoyed a career as a software engineer spanning many industries, including Point of Sale systems, investment management systems, and mobile payment systems. Currently employed as a backend/API engineer for Travelstart, Africa's leading online travel agency, Michael spends his whole day, practically every day, working with Java and Android. In his spare time, Michael is a Kendo practitioner and enjoys playing Ingress to get out and about.
For support files and downloads related to your book, please visit www.PacktPub.com.
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 [email protected] 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.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788475054.
If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
Creating Android Layouts
Material Design
Android Studio
Android application structure
Creating SimpleLayout
Discovering the layout editor
Organizing project files
Summary
Designing Form Screens
Exploring form screens
Designing a layout
Creating a form layout
Creating the description box
Adding the amount and date inputs
Creating the category chooser
Making icons change with state
Creating the category picker layout
Adding the attachment preview
Try it yourself
Test your knowledge
Summary
Taking Actions
Understanding Android event requirements
Listening for some events
Wiring the CaptureClaimActivity events
Handling events from other activities
Making events quick
Multiple event listeners
Test your knowledge
Summary
Composing User Interfaces
Designing a modular layout
Creating the DatePickerLayout
Creating the data model
Creating the Attachment class
Creating the Category enum
Creating the ClaimItem class
Wrapping up the category picker
Creating the Attachment Pager
Creating the Attachment preview widget
Creating the Attachment Pager Adapter
Creating the Create Attachment Command
Creating the Attachment Pager Fragment
Capturing the ClaimItem data
Try it yourself
Test your knowledge
Summary
Binding Data to Widgets
Exploring data models and widgets
The Observer pattern
Enabling data binding
Data binding a layout file
Creating an Observable model
Establishing the AllowanceOverviewFragment
Creating the AllowanceOverview layout
Updating the SpendingStats class
Data binding and fragments
Test your knowledge
Summary
Storing and Retrieving Data
Data storage in Android
Using the SQLite database
Introducing Room
Adding Room to the project
Creating an Entity model
Creating the Data Access Layer
The LiveData class
Implementing Data Access Objects in Room
Creating a database
Accessing your Room database
Test your knowledge
Summary
Creating Overview Screens
Designing an Overview screen
Elements of an Overview screen
Creating layouts for ViewHolders
Creating a simple ViewHolder class
Creating a ViewHolder with data binding
Creating a RecyclerView adapter
Data binding an adapter
Creating the Overview activity
Creating new ClaimItems with a Fragment
Allowance overview with a Room database
Test your knowledge
Summary
Designing Material Layouts
Looking at material structure
Introducing CoordinatorLayout
Coordinating the Overview Screen
Swiping to delete
Elevating widgets
Building layouts using grids
Stack view
Test your knowledge
Summary
Navigating Effectively
Planning navigation
Tabbed navigation
Bottom tabs navigation
Navigation menus
Navigating using Fragments
Test your knowledge
Summary
Making Overviews Even Better
Multiple view types
Introducing dividers
Updating by Delta Events
Test your knowledge
Summary
Polishing Your Design
Choosing colors and theming
Producing an application palette
Generating palettes dynamically
Adding animations
Creating custom animations
Activating more animations
Creating custom styles
Test your knowledge
Summary
Customizing Widgets and Layouts
Creating custom view implementations
Integrating the SpendingGraphView
Creating a layout implementation
Creating animated views
Test your knowledge
Apply your knowledge
Summary
Activity Lifecycle
Test Your Knowledge Answers
Chapter 2 - Designing Form Screens
Chapter 3 - Taking Actions
Chapter 4 - Composing User Interface
Chapter 5 - Binding Data to Widgets
Chapter 6 - Storing and Retrieving Data
Chapter 7 - Creating Overview Screens
Chapter 8 - Designing Material Layouts
Chapter 9 - Navigating Effectively
Chapter 10 - Making Overviews Even Better
Chapter 11 - Polishing Your Design
Chapter 12 - Customizing Widgets and Layouts
User interfaces represent the single most important aspect of any modern mobile application. They are the primary point of contact with your user, and a good user interface can be the difference between the success and failure of an application. This book will guide you down the path of user interface excellence, teaching you the techniques of great user interface design for Android, and showing you how to implement them.
Building user interfaces is all about building for the user and making their lives easier. It's important that the user interface helps the user achieve their goals within the application without distracting them. This means that each screen must serve a purpose, and every widget must work for its place on the screen. Widgets that are seldom used are distractions and should be moved, or removed, from the application entirely.
User interfaces are not just about pretty colors, fonts, and graphics; they are at the heart of the user experience within an application. How you create your user interfaces is built on the underlying structures you build in your applications code base. If the foundations of the application are not solid, the user experience will suffer. Every action taken by the user should have a quick and positive result, reinforcing their confidence that they can reach their goals within the application.
In this book, we'll be exploring not just how to write user interface code, but how to go about designing great user interfaces as well. We'll look at how lower layers like data storage can impact the user experience, and how to leverage the Android platform and its support libraries to build better applications, applications that look great, run fast, and help ensure that the user can understand the application quickly and is guided through with minimal distractions.
Chapter 1, Creating Android Layouts, will introduce or reintroduce Android Studio and help create a new Android application project from a template. We'll look at how an Android project is structured and how a user interface is wired together.
Chapter 2, Designing Form Screens, will show you how to design a form screen from scratch. You will learn techniques to decide what to put on the screen and how to layout a form screen to maximize its effectiveness while not disrupting your user's flow of thought.
Chapter 3, Taking Actions, will show you how to handle events in Android. It'll walk you through various types of events and provide you patterns and techniques to keep your application as responsive as possible. It'll also show you techniques to avoid complexity overload in your code base and how to keep your application's internal structure as clean as possible.
Chapter 4, Composing User Interfaces, will give you tools to build modular user interface components. It'll show you how to wrap related logic and user interface structures so that they can be reused, to reduce your code complexity while also making the user experience more consistent.
Chapter 5, Binding Data to Widgets, will introduce the data binding framework in Android. You'll find out why data binding exists, how it works, and how to use it effectively. You'll learn how to create user interface structures that automatically update when the data model changes.
Chapter 6, Storing and Retrieving Data, will cover how the storage and retrieval of data in a mobile app has a direct effect on the user experience. You will learn how best to build offline-first, reactive applications using the Room data access layer and data binding.
Chapter 7, Creating Overview Screens, will explore the RecyclerView and how it is often used in overview screens and dashboards to provide information. You'll learn how to create the data structures that support a RecyclerView and how to leverage data binding to massively reduce the boilerplate traditionally associated with these structures.
Chapter 8, Designing Material Layouts, will introduce several Material Design-specific patterns and widgets for Android apps. You'll learn how to leverage collapsing title bars and customize them to show your user additional information. You'll also learn how to add swipe-to-dismiss behavior, undo snackbars, and elevation to your user interfaces.
Chapter 9, Navigating Effectively, will help you learn to make a design-effective application navigation to guide your user to their intended goals intuitively. This chapter introduces several navigation-specific widgets and layout techniques, and shows where and how they can be most effectively applied.
Chapter 10, Making Overviews Even Better, will revisit the overview screen built in Chapter 7, Creating Overview Screens, and show how to leverage the Android platform API to produce polished overview screens. You'll learn how to use DiffUtil to automatically produce animations in RecyclerView and patterns that allow you to produce more readable overview lists.
Chapter 11, Polishing Your Design, will help you with the polishing of a good design. It'll introduce tools and techniques to help you choose a color scheme for your application. You'll also learn how to generate color schemes on the fly and how to create and use animations to guide your users.
Chapter 12, Customizing Widgets and Layouts, will introduce building your own custom widgets for Android. You'll learn how to render 2D graphics directly from Java code and how to create your own custom layouts. This chapter also shows how to build animation widgets that self-animate while they are visible.
Appendix A, Activity Lifecycle, a diagram and short description covering the lifecycle events delivered to an Android Activity, and when they can be delivered.
Appendix B, Test Your Knowledge Answers, the answers to the Test Your Knowledge section of each chapter.
You'll need to download and install at least Android Studio 3.0. Using Android Studio, you will need to download a recent Android SDK so that you can compile and run your code.
This book is for novice Android and Java developers who have basic knowledge of Android development and want to start developing stunning user interfaces.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The next lines of code read the link and assign it to theconstantSizeattribute." A block of code is set as follows:
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:constantSize="true" android:exitFadeDuration="@android:integer/config_shortAnimTime" android:enterFadeDuration="@android:integer/config_shortAnimTime">
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:constantSize="true"
android:exitFadeDuration="@android:integer/config_shortAnimTime" android:enterFadeDuration="@android:integer/config_shortAnimTime">
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "In order to download new modules, we will go toFiles|Settings|Project Name|Project Interpreter."
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply email [email protected], and mention the book's title in 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 at www.packtpub.com/authors.
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.
You can download the example code files for this book 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 emailed directly to you. You can download the code files by following these steps:
Log in or register to our website using your email address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Hands-On-Android-UI-Development. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
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 could 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 to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted 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 [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
Mobile App user interfaces have come a long way from the early days, and while users have more devices to choose from than ever, they all expect consistently high-quality experiences from their apps. Apps are expected to run fast and the user interfaces are expected to be smooth; all this while running on a massive array of devices of varied capabilities. Your app needs to run on devices with screens as big as televisions on the one end of the scale, and smartwatches with screens as small as 2.5 cm or even smaller on the other end of the scale. At first glance, this may seem like a nightmare, but there are simple tricks to make building responsive Android apps easy.
In this book, you'll learn a diverse set of skills as well as some theoretical knowledge that you can apply to build fast, responsive, and great-looking Android applications. You'll learn how to go about designing the screens that your application will actually need, and then how to build them for maximum flexibility and performance while keeping your code easy to read and avoiding bugs.
In this chapter, we will look at the basic principles used to build user interfaces for Android applications. You'll need to be familiar with concepts to build even the simplest Android application, so in this chapter, we'll cover the following topics:
The basic structure of an Android application
Creating a simple Activity and layout files using Android Studio
Where to find the most useful parts of the Android Studio layout editor
How a well-organized project is structured
Since Android was first introduced in 2008, the user interface design has changed radically, from the first early versions of the grey, black, and orange theme, to the Holo theme, which was more of a stylistic change than a fundamental shift in the design language, and eventually culminating in material design. Material Design is more than just a style; it's a design language complete with concepts for navigation, and overall application flow. Central to this idea is the notion of paper and card, the idea that the items on the screen are not simply next to each other but may also be above and below in the third dimension (although this is virtual). This is achieved using the elevation property that is common to all widgets in Android. Along with this basic principle, material design offers some common patterns to help the user identify which components are likely to take which actions, even the first time they are used in the application.
If you look at the original Android theme alongside the Holo Light theme, you can see that while the style changed dramatically, many elements stayed similar or the same. The grey tones flattened, but are very similar, and many of the borders were removed, but the spacing remains very close to the original theme. The material design language is often very similar in its basic styling and design to Holo:
The design language is an essential part of modern user interface design and development. It not only defines the look and feel of your widget toolkit, but also defines how the application should behave on different devices and in different circumstances. For example, on Android, it is common to have a navigation drawer since the slides are from the left, while this would not feel natural to the user on other platforms. Material design defines much more than the look and feel of navigation, it also includes guidelines for motion and animation, how to display various types of errors, and how to guide your users through an application for the first time. As a developer or designer, you may feel like this limits your creative freedom, and to some degree it actually does, but it also creates a clear message for your users on how your app expects to be used. This means that your users can use your app more easily, and it requires less cognitive load.
Another aspect of application development, which is of vital importance in any modern mobile application, is its performance. Users have come to expect that applications will always run smoothly, no matter the actual load on the system. The benchmark for all modern applications is 60 frames per second, that is, a full render event delivered to the user every 16.6 milliseconds.
Users don't just expect an application to perform well, they expect it to react instantly to external changes. When data is changed on the server side, users expect to see it on their device instantly. This makes the challenges of developing a mobile application, especially one with good performance, become even more difficult. Fortunately, Android comes with a fantastic toolset and an enormous ecosystem for dealing with these problems.
Android attempts to enforce good threading and performance behavior by timing each event that happens on the main thread and ensures that none of them take too long (and producing an Application Not Responding (ANR) error if they do). It further requires that no form of networking is conducted on the main thread, since these will invariably affect the application's performance. However, where this approach gets hard to work with is--any code related to the user interface must happen on the main thread, where all the input events are processed, and where all the graphics rendering code is run. This helps the user interface framework by avoiding any need for thread locks in what is very performance-centric code.
The Android Platform is a complete alternative to the Java Platform. While at a high level, the Android platform APIs are a form of Java framework; there are noticeable differences. The most obvious is that Android does not run Java bytecode, and does not include most of the Java standard APIs. Instead, most of the classes and structures you'll use are specific to Android. From this perspective, the Android platform is a bit like a large opinionated Java Framework. It attempts to reduce the amount of boilerplate code you write by providing you with skeleton structures to develop your applications.
The most common way to build user interfaces for Android is to do it declaratively in the layout XML files. You can also write user interfaces using pure Java code, but while potentially faster, it's not commonly used and carries some critical pitfalls. Most notably, the Java code is much more complex when handling multiple screen sizes. Instead of simply being able to reference a different layout file and have the resource system link in the best fit for the device, you have to handle these differences in your code. While parsing XML may seem a crazy idea on a mobile device, it's not nearly that bad; the XML is parsed and validated at compile time, and turned into a binary format which is what is actually read at runtime by your application.
Another reason it's really nice to write Android layouts in XML is the Android Studio layout editor. This gives you a real-time preview of what your layout will look like on a real device, and the blueprint view helps enormously when debugging issues like spacing and styling. There is also an excellent linting support in Android Studio that helps you avoid common problems before you're even finished writing your layout files.
Android Studio is a fully-featured IDE built on top of the IntelliJ platform, designed specifically for developing Android applications. It has a huge suite of built-in tools that will make your life better, and help you write better applications more rapidly.
You can download Android Studio for your favorite Operating System (OS) from https://developer.android.com/studio/. The setup instructions for each operating system vary slightly, and are available on the website. This book has been written assuming an Android Studio version of at least 3.0.
Once installed, Android Studio will also need to download and install an Android SDK for you to develop your applications on. There are platform options for virtually every version of Android ever released, including emulated hardware, which allows you to test how your application will run on different hardware and Android releases. It's best to download the latest Android SDK, and one of the older versions as well to check backward compatibility (4.1 or 4.4 are good options).
An Android application is very different in its internal structure when compared to applications on other platforms, in even the simplest details. Most platforms see their applications as monolithic systems with a fixed entry point. When the entry point returns or exits, the platform assumes that the application has finished running. On Android, an application may have several different entry points for the user, and others for the system. Each entry point has a different type, and different ways for the system to reach it (called intent filters). The most important part of an application from the user perspective is its activities. These (as the name suggests) are supposed to represent an action that the user will take with the application, such as the following:
List my emails
Compose an email
Edit a contact
Each Activity is a non-abstract class extending the Activity class (or any descendant of Activity), and registers itself and its intent filters in the application manifest file. Here's an example of how the manifest entry for an Activity that can view and edit contacts might look:
<activity android:name=".ContactActivity"> <intent-filter> <!-- Appear in the launcher screen as the main entry point of the application --> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <!-- Handle requests to VIEW Uris with a mime-type of 'data/contact' --> <action android:name="android.intent.action.VIEW" /> <data android:mimeType="data/contact"/> </intent-filter> <intent-filter> <!-- Handle requests to EDIT Uris with a mime-type of 'data/contact' --> <action android:name="android.intent.action.EDIT" /> <data android:mimeType="data/contact"/> </intent-filter></activity>
Each Activity is typically intended to do a single thing from the user's perspective, but this is not always the case. In the preceding case, there are three possible intent filters, each of which telling the system something different about the ContactActivity class:
The first one tells the system that
ContactActivity
should have its icon displayed on the launcher screens, effectively making it the main entry point of the application
The second tells the system that
ContactActivity
can be used to
VIEW
content with a mime-type of
"data/contact"
The third tells the system that
ContactActivity
can also be used to
EDIT
content with the
"data/contact"
mime-type
An Activity will generally have a primary layout file defined as an XML resource. These layout resource files are generally not standalone, but will make use of other resources and even other layout files.
The resource system in Android needs some special attention, as it allows for multiple files to collaborate together to create complex behavior out of simple components. At its heart, the resource system selects the most appropriate of each resource when it is requested (including from inside other resources). This not only allows you to create screen layouts for portrait and landscape mode, but allows you to do the same for dimensions, text, colors, or any other resource. Consider the following example:
<!-- res/values/dimens.xml --><
dimen
name=
"grid_spacer1"
>
8dp
</
dimen
>
The above dimension resource can now be used in layout resource files by name:
<!-- res/layouts/my_layout.xml --><
LinearLayout
android
:layout_width=
"match_parent"
android
:layout_height=
"match_parent"
android
:layout_margin=
"
@dimen/grid_spacer1
"
>
Using this sort of technique, you can adjust layouts for different screen sizes by simply changing the distance measurements used to space and size the widgets, rather than having to define completely new screen layouts.
Now that we've gone over the basics of an Android application structure, let's create a simple screen and see how things all fit together. We'll use Android Studio and one of its wonderful template activities. Just follow these easy steps:
Start by opening Android Studio on your computer.
Start a new project using the
File
menu, or the quickstart dialog (depending on which one shows up for you).
Name the project as
SimpleLayout
, and leave any additional support (C++, Kotlin) off:
On the next screen of the New Project wizard, ensure that you support Android 4.1 or higher, but leave only
Phone and Tablet
checked for this task:
Android Studio comes with a fantastic selection of
Activity templates
available on the next screen. This will be the first
Activity
generated to get you started with your project. For this example, you'll want to scroll down the list and find
Navigation Drawer Activity
. Select it and click on
Next
:
Leave the Activity details as their defaults (MainActivity, and so on) and click on Finish to complete the New Project wizard. Android Studio now creates your project and runs a first build-sync over to get everything working.
Once your project has finished being generated, you'll be presented with the Android Studio layout editor, looking something like this:
Congratulations, this template provides an excellent starting point to explore how Android applications and their user interfaces are built and fit together.
At first glance, the layout editor in Android Studio is a standard WYSIWYG editor; however, it has several important features that you need to be aware of. Most importantly, it actually runs the code for the widgets in order to render them within the editor. This means that if you write a custom layout or widget, it will look and behave as it will on the emulator or on a device. This is fantastically useful for rapidly prototyping screens, and can drastically cut down on development time when used properly.
To ensure that your layout is being rendered correctly, you'll sometimes need to ensure that the layout editor is configured correctly. From the toolbar at the top of the layout editor, you can select the virtual device configuration you would like it to emulate. This includes whether the layout is being viewed in portrait or landscape mode, and even what language settings to use for the layout rendering and resource selection:
It's important to keep in mind that the list of available Android platform versions that the layout editor can emulate is limited, and it is not connected to the list that you have installed as virtual devices (so you cannot add new versions to the layout editor by installing additional platform versions). If you want to see how your user interfaces of versions that Android Studio doesn't directly support look, the only way to do it is to run the application.
The next really important thing to note is the attributes panel, which is docked to the right of the layout editor by default. When you select a component in the design area, the attributes panel allows tweaking of all the attributes that can be changed in XML, and of course, you get to see the results of any changes live in the layout editor:
The number of attributes is generally kept well under control by Android Studio. The default panel only shows the most commonly used attributes for the selected widget. To toggle between this shortlist and the list of all the available attributes (something you'll do more often than you think), you'll want to use the toggle button () at the top of the attributes panel.
However, when you look at the All Attributes view, you'll note that their sheer number makes the view rather difficult to use. The easiest way to solve this is to use the search button () to find the attribute you're looking for. This will allow you to search for attributes by name, and is the quickest way to filter the list and get to the attribute, or group of attributes, that you're looking for (that is, scroll will give you all the attributes containing the word scroll, including scrollIndicators, scrollbarSize, scrollbarStyle, and so on).
As you saw, an Android application comprises of more modular components, which assemble in layers, and are often directly accessible from the platform. The resource management system is your greatest ally and should be leveraged to provide your users with a consistent experience, and keep your user interface consistent. When it comes to arranging your application, Android Studio has a variety of tools and features that it will use to help you keep things organized and within commonly understood patterns. However, it's also important to stick to your own patterns and keep things organized. The Android toolkits have their own requirements, and you'll need to obey their rules if you want to benefit from them.
Android Studio also has an excellent collection of template projects and Activities, and they should be used to get your projects kick-started. They can also often serve with explanations for how common user interface design patterns are implemented in Android.
In the next chapter, we'll take a look at starting a layout from scratch and how to approach designing a form screen.
Form screens are an essential part of user interface design in many ways because their history is a lesson in how not to do things. Most applications need to capture input from their users at some point, and you need input widgets for that, but you should always consider the minimum amount of information you need to ask the user for, rather than try to get all the information you may need in the future. This approach will keep the user focused on the task they are trying to carry out. Presenting them with a wall of input fields is overwhelming to most users and breaks their focus, which in turn can lead to them abandoning what they were trying to do with your application.
This chapter is focused on form screens, and will walk you through a bit of their history before diving into a method for actually designing form screens. This approach can and should be reused whenever you need to design a screen for an app. It's always important to take a step back from your code work and consider how things will look and fit together for the user; it's often the difference between a successful app and failure.
In this chapter, we'll develop a practical form screen using Android Studio and the layout editor. Starting from an empty template in a new project, you'll learn the following:
How to break up and then arrange a form layout to be most effective for your users
How to use resources to keep your user interface consistent
How to style widgets to help the user understand what the widget should be used for
How to build drawable resources that respond to state changes
While not the most glamorous component of an application's user experience, form screens are a long-time staple of software. A form screen can be defined as any screen where the user is expected to explicitly enter or change data, as opposed to viewing or navigating it. Good examples of form screens are login screens, edit profile screens, or the add contact screen from a phonebook app. Over the years, the idea of what constitutes a good form screen has changed, with some people going as far as to shun them completely. However, you can't capture the user's data out of thin air.
The Android standard toolkit provides an excellent and diverse collection of widgets and layout structures to facilitate building excellent forms, and in Material Design applications, form screens can often double as a view screen (what will usually be a read-only version of the form screen) thanks to the placement of labels. A good way to understand this principle is to consider the evolution of textboxes. As soon as you have a blank space to be filled by your user, you need to tell the user what to put there, and when we started labeling textboxes, we simply copied how we did this on paper forms--by putting a label to the one side of the textbox:
