Mastering Android Studio - A Beginner's Guide
Mastering Android Studio - A Beginner's Guide
Studio
Mastering Computer Science
Series Editor: Sufyan bin Uzayr
DOI: 10.1201/9781003229070
Typeset in Minion
by KnowledgeWorks Global Ltd.
Contents
v
vi ◾ Contents
Heap Dump 18
Memory Profiler 18
Data File Access 19
Code Inspections 19
Annotations in Android Studio 19
Log Messages 20
Sign in to Your Developer Account 20
A BRIEF HISTORY OF ANDROID STUDIO 20
ADVANTAGES OF ANDROID DEVELOPMENT 25
DISADVANTAGES OF ANDROID
DEVELOPMENT 25
EXPLORING ANDROID STUDIO 31
APPRAISAL, 227
INDEX, 237
About the Editor
xiii
Chapter 1
Introduction to
Android Studio
IN THIS CHAPTER
DOI: 10.1201/9781003229070-1 1
2 ◾ Mastering Android Studio
they have added live hints so that while you are coding,
you will get suggestions to make necessary changes that
can fix errors or make your code sharper. Moreover, in case
a variable is not being used, it will be highlighted in grey.
And once you start typing a line of code, Android Studio
will provide a list of autocomplete suggestions to help you
finish it, which is great for when you cannot quite remem-
ber the correct syntax or you just want to save some time.
The following is a list of Android Studio’s major releases1:
Version-Release date
4.2 May 2021
4.1 October 2020
4.0 May 2020
3.6 February 2020
3.5 August 2019
3.4 April 2019
3.3 January 2019
3.2 September 2018
3.1 March 2018
3.0 October 2017
2.3 March 2017
2.2 September 2016
2.1 April 2016
2.0 April 2016
1.5 November 2015
1.4 September 2015
1.3 July 2015
1.2 April 2015
1.1 February 2015
1.0 December 2014
1 https://developer.android.com/studio/releases, Android
6 ◾ Mastering Android Studio
2 https://developer.android.com/studio, Android
Introduction to Android Studio ◾ 7
MAJOR FEATURES
Every project started in Android Studio contains one or
more modules with source code files and resource files.
Standard types of modules include Android app modules,
Library modules, and Google App Engine modules.
Normally, Android Studio displays project files in the
Android project view to provide quick access to your proj-
ect’s key source files. Thus, all the build files should be
visible at the top level under Gradle Scripts, and each app
module should have the following folders:
Tool Windows
Instead of using preset options, Android Studio follows the
original context to be able to automatically bring up rel-
evant tool windows as you work. By default, the most com-
monly sought tool windows are pinned to the tool window
bar at the edges of the application window.
3 https://developer.android.com/studio/intro, Android
12 ◾ Mastering Android Studio
Navigation
We shall cover the navigation option in depth later in
Chapter 4 of this book. But the basic features include the
following:
You can switch between your recently accessed files
applying the Recent Files action. To bring up the Recent
Files action press Control+E (Command+E on a Mac) and
by default, the last accessed file will be selected. You can
also access any tool window through the left column in this
action.
In case you need to view the structure of the current file, you
can use the File Structure action. Bring up the File Structure
action by pressing Control+F12 (Command+F12 on a Mac)
and quickly navigate to any part of your current file.
4 https://developer.android.com/studio/intro, Android
TABLE 1.2 Basic Keyboard Shortcuts
Type Description Windows and Linux Mac
Basic completion Displays basic suggestions for variables, Control+Space Control+Space
types, methods, expressions, etc. If you
call basic completion twice in a row,
you see more results, including private
independently from the command line. You can use the fea-
tures of the build system to complete the following:
Build Variants
The build system assists in the creation of different versions
of the same application from a single project. This is par-
ticularly useful when you have both a free version and a
paid version of your app or in case you need to distribute
multiple Android application packages for different device
configurations on Google Play.
Resource Shrinking
Resource shrinking in Android Studio automatically gets
rid of unused resources from your packaged app and
library dependencies. For example, if your application is
using Google Play services to access Google Drive func-
tionality, and you are not currently using Google Sign In,
then resource shrinking can delete the various assets for
the Sign In buttons.
Managing Dependencies
Dependencies for your project are identified by name in
the build.Gradle file. Gradle is responsible for search-
ing for your dependencies and making them available in
your build. You can declare module dependencies, remote
binary dependencies, and local binary dependencies in
your build.Gradle file. Android Studio configures projects
to use the Maven Central Repository that is included in the
top-level build file for the project by default.
Performance Profilers
Android Studio provides performance profilers so you can
track your app’s memory and central processing unit usage,
search deallocated objects, locate memory leaks, optimize
graphics performance, and analyze network requests.
Heap Dump
When you are profiling memory usage in Android Studio,
you can simultaneously initiate garbage collection and
dump the Java heap to a heap snapshot in an Android-
specific A Heap/CPU Profiling Tool (HPROF) binary for-
mat file. The HPROF viewer shows classes, instances of
each class, and a reference tree to assist you in tracking
memory usage and find memory leaks.
Memory Profiler
You can use Memory Profiler to trace memory alloca-
tion and check where objects are being placed when you
Introduction to Android Studio ◾ 19
Code Inspections
Every time you compile your program, Android Studio
automatically runs configured Lint and other IDE inspec-
tions to help you identify and fix problems with the struc-
tural quality of your code.
The Lint tool revises your Android project source files
for potential bugs and optimization improvements for cor-
rectness, security, quality, usability, accessibility, and inter-
nationalization. In addition to Lint checks, Android Studio
also completes IntelliJ code inspections and verifies anno-
tations to add to your coding workflow.
Log Messages
Once you build and run your app with Android Studio,
you can view adb output and device log messages in the
Logcat window. In case you need to profile your app’s cen-
tral processing unit, memory, and network performance,
just access the Android Profiler by clicking View > Tool
Windows > Android Profiler.
5 https://gs.statcounter.com/os-market-share/mobile/worldwide, Statcounter
Introduction to Android Studio ◾ 23
Getting Started
with Android
Studio
IN THIS CHAPTER
Windows
If you are installing Android Studio on Windows, be sure
to proceed with the following steps: In case you down-
loaded an .exe file, just double-click to launch it. If you
downloaded a.zip file, you first need to unpack the ZIP,
copy the android-studio folder into your Program Files
folder, and then open the android-studio > bin folder and
launch studio64.exe (for 64-bit machines) or studio.exe
(for 32-bit machines).
Getting Started with Android Studio ◾ 35
Mac
If you are a Mac user, the setup process is pretty straight-
forward as it is:
and this prompt occurs, you can always go with the Do Not
Allow option.
Linux
In order to install Android Studio on Linux, proceed as
follows:
Unpack the .zip file you downloaded to a suitable loca-
tion for your applications, such as within /usr/local/ for
your user profile, or /opt/ to share with others. In case
you are using a 64-bit version of Linux, you need to install
the required libraries for 64-bit machines first. But at the
same time, if you are running a 64-bit version of Ubuntu,
you should install some 32-bit libraries with the following
command1:
1 https://developer.android.com/studio/install, Android
Getting Started with Android Studio ◾ 37
Chrome OS
If you are a Chrome OS user, follow these steps for full
installation:
• In case you have not already done so, install Linux for
Chrome OS.
• Open the Files app and locate the DEB (Debian
Software Package file) you downloaded in the
Downloads folder under My files.
• Right-click the DEB package and select Install with
Linux (Beta).
• Choose the target file location for DEB package on
Chrome OS.
• If you have installed Android Studio previously, select
whether you want to import basic Android Studio
settings again or not, then click OK.
• Windows
Syntax: %APPDATA%\Google\<product><version>
Example: C:\Users\YourUserName\AppData\Roaming\
Google\AndroidStudio4.1
• MacOS
Syntax: ~/Library/Application Support/Google/<pro
duct><version>
Example: ~/Library/Application Support/Google/
AndroidStudio4.1
• Linux
Syntax: ~/.config/Google/<product><version>
Example: ~/.config/Google/AndroidStudio4.1
• Windows: %USERPROFILE%\.CONFIGURATION_
FOLDER
• MacOS: ~/Library/Preferences/CONFIGURATION_
FOLDER
• Linux: ~/.CONFIGURATION_FOLDER
android {
compileOptions {
sourceCompatibility JavaVersion.
VERSION\_1\_6
targetCompatibility JavaVersion.
VERSION\_1\_6
}
}
Proxy Settings
Proxies could be defined as intermediary link points
between HTTP clients and web servers that are responsible
for ensuring the security and privacy of internet connec-
tions. In order to support running Android Studio behind
a firewall, it is necessary to set the proxy proper for the
Android Studio IDE. You can use the Android Studio IDE
HTTP Proxy settings page to set the HTTP proxy settings
for Android Studio. From the menu bar, navigate to File >
Settings (on MacOS, click Android Studio > Preferences).
In the left pane, you should click on Appearance & Behavior
> System Settings > HTTP Proxy. When the HTTP Proxy
page appears, opt for Auto-detect proxy settings if you
need to use an automatic proxy configuration URL for the
proxy settings, or you can click on Manual proxy configu-
ration to be able to enter each of the settings yourself. Click
Apply or OK to save your changes.
46 ◾ Mastering Android Studio
• Syntax: %LOCALAPPDATA%\Google\<product>
<version>
• Example: C:\Users\YourUserName\AppData\Local\
Google\AndroidStudio4.1
Sensible Defaults
Gradle is founded on a concept referred to as conven-
tion over configuration. Simply put, it means that Gradle
has a pre-determined number of sensible default con-
figuration settings that will be applied by default unless
they are disabled by settings in the build files. This also
means that builds can be administered with the minimum
50 ◾ Mastering Android Studio
Dependencies
Another key item that ensures Gradle functionality is
that of dependencies. For instance, a module within an
Android Studio project activates a motion to load another
module in the project. The first module has a dependency
on the second module since the application will fail to
build if the second module cannot be found and launched
at runtime. This dependency can be observed in the Gradle
build file for the first module so that the second module is
attached in the application build, or a random error in the
event of the second module cannot be found or built. Other
examples of dependencies could be libraries and JAR files
on which the project relies to compile and run.
Typically, Gradle dependencies are classified as local
or remote. A local dependency stands for an item that is
located on the local file system of the computer on which
the build is being operated. A remote dependency, on the
other hand, refers to an item that is located on a remote
server (also named as a repository).
Most times remote dependencies are handled for
Android Studio projects through another project man-
agement product named Maven. In case a remote depen-
dency is established in a Gradle build file using Maven
syntax, then the dependency will be downloaded auto-
matically from the identified repository and added to the
build process. The following dependency declaration, for
example, causes the AppCompat library to be included in
Getting Started with Android Studio ◾ 51
Build Variants
In addition to previously mentioned tools, Gradle also has
a build variant support for Android Studio projects. This
allows multiple variations of an application to be created
from a single project. And since Android operates on many
different devices encompassing a range of processor types
and screen sizes it is important to target as many device
types and sizes as possible to be able to build a number of
different variants of an application (with a user interface
for phones as well as for tablet-sized screens). Now, through
the extensive use of Gradle, it is possible in Android Studio.
Manifest Entries
It is considered acceptable that every Android Studio proj-
ect has accompanied with it an AndroidManifest.xml file
holding configuration data about the application. A num-
ber of manifest entries can be defined in Gradle build files
which are then auto-generated into the manifest file when
the project is executed. This capacity is strictly additional
to the build variants feature, allowing features such as the
application version number, application ID, and SDK ver-
sion information to be modified differently for each build
version.
ProGuard Support
ProGuard is a tool that comes with Android Studio that
optimizes, merges, and compiles Java byte code to make
it more productive but at the same time more difficult to
52 ◾ Mastering Android Studio
2 https://developer.android.com/studio/build/gradle-tips#groovy, Android
Getting Started with Android Studio ◾ 53
3 https://developer.android.com/studio/build/gradle-tips#groovy, Android
54 ◾ Mastering Android Studio
android {
…
testBuildType "production"
}
storePassword=myStorePassword
keyPassword=myKeyPassword
4 https://developer.android.com/studio/build/gradle-tips#groovy, Android
58 ◾ Mastering Android Studio
keyAlias=myKeyAlias
storeFile=myStoreFileLocation
Second, in your build.gradle file, you need to load the key-
store.properties file in the following manner (this has to be
before the android block):
//Creates a variable called keystorePropertiesFile, and
initializes it to the
//keystore.properties file.
def keystorePropertiesFile = rootProject
.file("keystore.properties")
Once you are done with that, just input the signing infor-
mation stored in the keystoreProperties object:
android {
signingConfigs {
config {
Getting Started with Android Studio ◾ 59
keyAlias keystoreProperties
['keyAlias']
keyPassword keystoreProperties
['keyPassword']
storeFile file(keystoreProperties
['storeFile'])
storePassword keystoreProperties
['storePassword']
}
}
...
chmod +x gradlew
Modules
A module is one of the key items of the project. It stands
for a collection of source files and build settings that let you
divide your project into separate units of execution. Your
project can have one or many modules and one module
may use another module as a dependency. Nevertheless,
you can be sure that each module can be independently
built, tested, and debugged.
Additional modules are often used to create different
code libraries within the project or if you need to have mul-
tiple sets of code and resources for different device types,
such as phones and wearables, but at the same time ensure
62 ◾ Mastering Android Studio
that all the files are scoped within the same project and
share some code. You can add a new module to your proj-
ect by clicking File > New > New Module.
Android Studio has a few other distinct types of modules:
Feature Module
This module type represents a modularized feature of your
app that is closely related to Play Feature Delivery. For
instance, with feature modules, you can provide your users
with specific features on-demand or instant experiences
through Google Play Instant.
Library Module
Provides a location for your reusable code, which you can
apply as a dependency in other app modules or can use with
other projects. Judging strictly by structure, a library mod-
ule resembles app module a lot, yet when built, it results
in a code archive file instead of an APK, so it cannot be
installed on a device. In the Create New Module window,
Android Studio presents the following library modules:
dependencies {
implementation project
(':my-library-module')
}
Project Files
By default, Android Studio keeps your project files in the
Android view. However, this view does not reflect the
actual file structure on disk, but simply organized by mod-
ules and file types to let you navigate between key source
files of your project, or be able to remove certain files or
directories that are not often used. Some of the structural
adjustments compared to the structure on disk include the
following:
5 https://www.programmersought.com/article/35024001299/, ProgrammerSought
66 ◾ Mastering Android Studio
sample code for your new project. But remember that you
are not limited to using only that language creating the proj-
ect. After that, select the Minimum API level you want your
app to support. Once you select a lower API level, your app
can rely on fewer modern Android APIs. However, a larger
percentage of Android devices are able to run your app. The
opposite is also true when selecting a higher API level.
In case you need your project to utilize AndroidX librar-
ies by default, which stand for an improved version of the
Android Support libraries, check the box next to the Use
AndroidX item. When you are ready to create your project,
simply click Finish.
Android Studio can create your new project with just
basic code and minimum resources. However, if you later
decide to add support for a different device form factor, you
can include a module in your project later. And if you want
to share code and resources between modules, you can do
so by establishing an Android library.
6 https://developer.android.com/guide/playcore/feature-delivery, Android
74 ◾ Mastering Android Studio
you can set custom ProGuard rules with each feature mod-
ule using the proguardFiles property, as shown here:
android.buildTypes {
release {
// You must use the following
property to specify additional ProGuard
// rules for feature modules.
proguardFiles 'proguard-rules-
dynamic-features.pro'
}
}
7 ttps://developer.android.com/guide/playcore/feature-delivery, Android
h
8 https://developer.android.com/guide/playcore/feature-delivery, Android
TABLE 2.1 Features Delivery Options
Delivery Option Behavior Sample Use-Case Getting Started
Install-time Feature modules that do not configure any of You can include that feature at app Modularize your app using
delivery the delivery options are downloaded at app install, by default. However, to feature modules that
install, by default. This is an important reduce the installed size of the configure no advanced
behavior because it means that you can adopt app, the app can request to delete delivery options.
advanced delivery options gradually. the feature after the user has .
In addition, your app can request to uninstall completed the training.
Android Studio
Basics
IN THIS CHAPTER
DOI: 10.1201/9781003229070-3 85
86 ◾ Mastering Android Studio
ANDROID STUDIO UI
A standard UI of Android Studio consists of an action bar
and the application content area. The action bar, typically
Android Studio Basics ◾ 87
very useful for the users, and developers were looking for
options to customize it.
Along with the Action bar, Google includes a support
library that is a part of AppCompat which purpose is to pro-
vide backward compatibility for older versions of Android
and to operate tabbed interfaces. All applications that use
the default theme provided by the Android (project name
is – Theme.AppCompat.Light.DarkActionBar), contains
an Action Bar by default. However, developers can mod-
ify it in several ways depending upon their requirements.
Components included in the Action Bar are:
<activity
android:name="com.example.actionbar.
MainActivity"
1 https://www.sitepoint.com/better-user-interfaces-android-action-bar/, Site
Point
Android Studio Basics ◾ 93
android:label="@string/app_name"
android:uiOptions="splitActionBarWhenNar
row" >
<meta-data android:name="android.support.
UI_OPTIONS"
android:value="splitActionBarWhenNar
row" />
<intent-filter>
<action android:name="android.intent.
action.MAIN" />
<category android:name="android.intent.
category.LAUNCHER" />
</intent-filter>
</activity>
if(actionBar != null) {
if(actionBar.isShowing()) {
actionBar.hide();
}
else {
actionBar.show();
}
}
}
3 ttps://www.sitepoint.com/better-user-interfaces-android-action-bar/,
h Site
point
Android Studio Basics ◾ 95
<resources>
<style name="AppBaseTheme"
parent="android:Theme.Light">
</style>
LAYOUTS
Android Layout is used to define the UI that holds the
UI controls or widgets that are displayed on the screen of
your application or activity screen. As a general rule, every
application is a combination of View and ViewGroup. And
as we already stated, an android application contains a
large number of activities, and we can treat each activity
as one page of the application. Meaning, each activity con-
tains multiple UI components, and those components are
96 ◾ Mastering Android Studio
Layout Position
The geometry (shape) of a view is that of a rectangle. A view
also has a location, presented as a pair of left and top coor-
dinates, and two dimensions, that come as a width and a
height. The unit for location and dimensions is the pixel.
If required, you can retrieve the location of a view by
invoking the methods getLeft() and getTop(). The former
returns the left, or X, coordinate of the rectangle represent-
ing the view. The latter returns the top, or Y, coordinate of
the rectangle representing the view. These methods both
return the location of the view relative to its parent. To
illustrate, when getLeft() returns 20, that means the view
is located 20 pixels to the right of the left edge of its direct
parent.
Moreover, there are several convenience methods are
offered to prevent unnecessary computations, namely
GetRight() and getBottom(). These methods return the
Android Studio Basics ◾ 97
android:layout_margin="16dp"
android:hint="Input"
android:inputType="text"/>
Once you have created the layout, now you need to load the
XML layout resource from the activity onCreate() callback
method and access the UI element from the XML using
findViewById:
You should observe the above code and see that we are
calling our layout using the setContentView method in
the form of R.layout.activity_main. Normally, during the
launch of our activity, the onCreate() callback method will
be retrieved by the android framework to get the required
layout for an activity.
Layouts are an essential segment of Android applica-
tions that directly affect the user experience. If designed
and executed poorly, your layout can lead to a memory-
hungry application with slow UIs. The Android SDK
has tools to assist you in identifying problems in your
layout performance, which will result in smooth scroll-
ing interfaces with a minimum memory footprint once
implemented.
It is a common misconception thinking that follow-
ing the basic layout structures leads to the most efficient
layouts. At the same time, each widget and layout you
include in your application requires initialization, layout,
and drawing. To illustrate with an example, using nested
instances of LinearLayout can lead to an excessively deep
view hierarchy. Moreover, nesting several instances of
LinearLayout that use the layout_weight parameter can
be particularly expensive as each child needs to be mea-
sured twice. This is particularly important when the layout
is inflated repeatedly, such as when used in a ListView or
GridView. However, there are certain things you can do to
optimize your layout performance:
102 ◾ Mastering Android Studio
Use Lint
It is always a good idea to run the lint tool on your layout
files to see if there are any possible view hierarchy optimi-
zations. Lint has replaced the Layoutopt tool and has much
greater functionality for such matters. Yet there are certain
lint rules you should be aware of before starting:
<FrameLayout xmlns:android="http://schemas.
android.com/apk/res/android"
xmlns:tools="http://schemas.android.
com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/
titlebar_bg"
tools:showIn="@layout/activity_main" >
<ImageView android:layout_width=
"wrap_content"
android:layout_height=
"wrap_content"
android:src="@drawable/
gafricalogo" />
</FrameLayout>
6 https://developer.android.com/training/improving-layouts/reusing-layouts,
Android
106 ◾ Mastering Android Studio
<LinearLayout xmlns:android="http://
schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/app_bg"
android:gravity="center_horizontal">
<TextView android:layout_width=
"match_parent"
android:layout_height=
"wrap_content"
android:text="@string/hello"
android:padding="10dp" />
</LinearLayout>
<include android:id="@+id/news_title"
android:layout_width=
"match_parent"
7 ttps://developer.android.com/training/improving-layouts/reusing-layouts,
h
Android
Android Studio Basics ◾ 107
android:layout_height=
"match_parent"
layout="@layout/title"/>
<merge xmlns:android="http://schemas.
android.com/apk/res/android">
<Button
android:layout_width="fill_parent"
8 ttps://developer.android.com/training/improving-layouts/reusing-layouts,
h
Android
108 ◾ Mastering Android Studio
android:layout_height=
"wrap_content"
android:text="@string/add"/>
<Button
android:layout_width="fill_parent"
android:layout_height=
"wrap_content"
android:text="@string/delete"/>
</merge>
STRINGS
A string element provides text strings for your application
with additional text styling and formatting. There are three
main types of strings that you can use in Android Studio:
In case you are wondering, all three strings styles are capa-
ble of applying some styling markup and formatting argu-
ments. Now let’s take a closer look at each string type.
Android Studio Basics ◾ 109
String
A single string can be referenced from the application as
well as from other resource files such as an XML layout. It
is considered to be a simple element that is referenced using
the value provided in the name attribute. It is also possible
to combine string resources with other simple resources in
one XML file, under one <resources> element.
The typical file location is at: res/values/filename.xml
The filename is arbitrary as the <string> element’s name
would later be used as the resource ID.
Standard resource references are:9
In Java: R.string.string_name
In XML:@string/string_name
String Array
An array of strings can too be referenced from the applica-
tion and be perceived as a simple resource that runs using
the value provided in the name attribute. In addition, you
can combine string array resources with other simple
resources in one XML file, under one <resources> element.
Standard file location is at: res/values/filename.xml
The filename is also arbitrary and the <string-array> ele-
ment’s name will later be used as the resource ID.
The resource reference in Java is: R.array.
string_array_name
Generic syntax to apply is:
10 https://developer.android.com/guide/topics/resources/string-resource,
Android
Android Studio Basics ◾ 113
At the same time, when you use this type of string, make sure
to add indicators showing its value. Valid values, with non-
exhaustive examples in parentheses, include the following:
Formatting Strings
In case you need to format your strings, then you can do so
by placing your format arguments in the string resource, as
illustrated by the following example:
<string name="welcome_messages">Hello,
%1$s! You have %2$d new messages.</string>
11 ttps://developer.android.com/guide/topics/resources/string-resource,
h
Android
Android Studio Basics ◾ 117
<resources>
<string name="welcome_messages">Hello,
%1$s! You have <b>%2$d new messages<
/b>.</string>
</resources>
VIEWS
Android offers a sophisticated and greatly componentized
model for building your UI, based on the fundamental lay-
out classes: View and ViewGroup. We have already gone
through a variety of prebuilt View and ViewGroup sub-
classes—called widgets and layouts, respectively—that you
can utilize to construct your UI.
A partial list of available widgets that we have men-
tioned included Button, TextView, EditText, ListView,
CheckBox, RadioButton, Gallery, Spinner, and the more
special-purpose AutoCompleteTextView, ImageSwitcher,
and TextSwitcher. Among the layouts available are
LinearLayout, FrameLayout, RelativeLayout, and others.
In case you find yourself in a situation where none of
the prebuilt widgets or layouts meets your needs, you can
always create your own View subclass. If you only need to
make small adjustments to an existing widget or layout,
you can simply subclass the widget or layout and override
its methods.
Creating your own View subclasses gives you precise
power over the appearance and function of all the screen
components. To give you a vague idea of the authority you
get with custom views, here are some examples of what you
could potentially do with them:
• You could create a completely custom-rendered View
type or a total volume control using 2D graphics that
resemble an analog electronic control.
• You could combine a group of View elements into a
new single component, in order to make something
like a ComboBox (a combination of popup list and
Android Studio Basics ◾ 119
12 ttps://developer.android.com/guide/topics/ui/custom-components?
h
hl=hi&skip_cache=true, Android
TABLE 3.1 Standard Methods and Their Definitions
Category Methods Description
Creation Constructors A form of the constructor is called when the view is created from code and a
form is called when the view is inflated from a layout file. The second form
should parse and apply any attributes defined in the layout file.
onFinishInflate() Called after a view and all of its children have been inflated from XML.
Layout onMeasure(int, int) Called to determine the size requirements for this view and all of its children.
onLayout(boolean, int, int, int, int) Called when this view should assign a size and position to all of its children.
onSizeChanged(int, int, int, int) Called when the size of this view has changed.
Drawing onDraw(Canvas) Called when the view should render its content.
Subclass a View
All of the view classes included in the Android frame-
work extend View. Your custom view can also extend View
directly, or you can save resources by extending one of the
existing view subclasses, such as Button.
In order to allow Android Studio to correspond to
your view, at a minimum you should provide a construc-
tor that takes a Context and an AttributeSet object as
parameters. This constructor allows the layout editor to
produce and edit an instance of your view, for instance,
126 ◾ Mastering Android Studio
<resources>
<declare-styleable name="PieChart">
<attr name="showText"
format="boolean" />
<attr name="labelPosition"
format="enum">
<enum name="left" value="0"/>
13 ttps://developer.android.com/guide/topics/ui/custom-components?
h
hl=hi&skip_cache=true, Android
Android Studio Basics ◾ 127
14 ttps://developer.android.com/guide/topics/ui/custom-components?
h
hl=hi&skip_cache=true, Android
128 ◾ Mastering Android Studio
init {
context.theme.obtainStyledAttributes(
attrs,
R.styleable.PieChart,
0, 0).apply {
try {
mShowText = getBoolean
(R.styleable.PieChart_showText, false)
textPos = getInteger
(R.styleable.PieChart_labelPosition, 0)
} finally {
recycle()
}
}
}
you may try exposing a property getter and setter pair for
each custom attribute. The following snippet illustrates
how PieChart exposes a property called showText:
Android Studio
Tools
IN THIS CHAPTER
$ wget https://dl.google.com/android/repository/tools_
r25.2.3-macosx.zip
After that you need to unzip and place the contents within
your home directory. The directory names can be anything
you like, but just make sure you save the files somewhere
easy to find. In order to run the SDK manager tool insert
the following features:
$ tools/bin/sdkmanager –update
$ tools/bin/sdkmanager “platforms;android-25”
“build-tools;25.0.2” “extras;google;m2repository”
“extras;android;m2repository”
$ tools/bin/sdkmanager –licenses
Android Studio Tools ◾ 137
export ANDROID_SDK_ROOT=/Users/android/
android-SDK-macosx
export PATH=$PATH:$ANDROID_SDK_ROOT/tools
$ source ~/.bash_profile
After that, choose the Android SDK Build-tools for the ver-
sion of Android that you listed in the build.Gradle file as
the android: buildToolsVersion target. If your build.gradle
says
android {
buildToolsVersion "21"
...
}
the AVD that you need to run your app on from the target
device drop-down menu and click Run.
In case you see an error or warning message at the top
of the dialog, click the link to correct the problem or to
get more information. Certain errors such as Hardware
Accelerated Execution Manager (Intel HAXM) errors you
should fix before you can continue.
For MacOS, if you see the following Warning: No DNS
servers found error when starting the emulator, check to
see whether you have an /etc/resolv.conf file. If you do not
have this file, enter the following command in a terminal
window:
ln -s /private/var/run/resolv.conf /etc/resolv.conf
1 https://developer.android.com/studio/run/emulator?hl=fr, Android
146 ◾ Mastering Android Studio
Snapshots
A snapshot is a stored image of an AVD that saves the
entire layout of the device at the time that it was saved –
including OS settings, application state, and user data. You
can address to a saved system state by loading a snapshot
anytime you want, saving you the time of waiting for the
operating system and applications on the virtual device
to restart, as well as saving you the resources of bringing
your app back to the state at which you want to continue
your testing. Starting a virtual device should be viewed as
waking a physical device from a sleep mode, as opposed to
knocking it from a powered-off state.
For each AVD, you can have one Quick Boot snapshot
and any number of general snapshots. The easiest way to
take advantage of snapshots is to use Quick Boot snap-
shots: By default, each AVD is set to automatically take a
Quick Boot snapshot on exit and load from a Quick Boot
snapshot on start.
The first time that an AVD starts, it should activate a cold
boot, just like powering on a device. If Quick Boot is enabled,
all subsequent starts load from the specified snapshot, and
the system is restored to the state scripted in that snapshot.
Snapshots are valid for the system image, AVD configu-
ration, and emulator features with which they are saved. In
148 ◾ Mastering Android Studio
System Images
A system image labeled with Google APIs normally
includes access to Google Play services. A system image
labeled with the Google Play logo in the Play Store column
Android Studio Tools ◾ 151
Storage Area
The AVD also has an additional storage area on your devel-
opment machine. It is mostly used to store the device user
data, such as installed apps and settings, as well as an emu-
lated SD card. If required, you can use the AVD Manager
to wipe user data, so the device has the same data as if it
were new.
Skin
To put it simply, an emulator skin is responsible for the
appearance of a device. The AVD Manager has some pre-
defined skins you can choose from. Additionally, you can
also define your own, or use skins specified by third parties.
Creating an AVD
To create a new AVD, open the AVD Manager by clicking
Tools > AVD Manager. Then choose Create Virtual Device,
at the bottom of the AVD Manager dialog. At the Select
152 ◾ Mastering Android Studio
An option is enabled only if it is selected in the hardware profile. When running the AVD in
the emulator, you can change the orientation if both portrait and landscape are supported in
the hardware profile.
(Continued)
TABLE 4.2 (Continued) AVD Properties List
The Emulated setting produces a software-generated image, while the Webcam setting uses
your development computer webcam to take a picture.
This option is available only if it is selected in the hardware profile.
Network: speed Select a network protocol to determine the speed of data transfer:
(advanced)
• GSM – Global System for Mobile Communications
• HSCSD – High-Speed Circuit-Switched Data
• GPRS – Generic Packet Radio Service
• EDGE – Enhanced Data rates for GSM Evolution
• UMTS – Universal Mobile Telecommunications System
• HSDPA – High-Speed Downlink Packet Access
• LTE – Long-Term Evolution
• Full (default) – Transfer data as quickly as your computer allows
Network: latency Select a network protocol to set how much time (delay) it takes for the protocol to transfer a
(advanced) data packet from one point to another point.
(Continued)
TABLE 4.2 (Continued) AVD Properties List
AVD Property Description
Emulated Select how graphics are rendered in the emulator:
performance:
graphics • Hardware – Use your computer graphics card for faster rendering.
• Software – Emulate the graphics in software, which is useful if you’re having a problem
with rendering in your graphics card.
• Automatic – Let the emulator decide the best option based on your graphics card.
Emulated • Cold boot – Start the device each time by powering up from the device-off state.
performance: boot • Quick boot – Start the device by loading the device state from a saved snapshot.
option (advanced)
Emulated Select the number of processor cores on your computer that you would like to use for the
Gradle Plugins
Before you can create your own navigation graph, you
need to take care of certain item dependencies. Thus, you
should add the following dependencies for the artifacts
you are going to use in the build.Gradle file for your app
or module3:
dependencies {
//For Java
– implementation “androidx.navigation:navigation-
fragment:$nav_version”
– implementation “androidx.navigation:navigation-ui:
$nav_version”
//For Kotlin
– implementation “androidx.navigation:navigation-
fragment-ktx:$nav_version_ktx”
– implementation “androidx.navigation:navigation-ui-
ktx:$nav_version_ktx”
After all the plugins are configured, you can start creating
Navigation component for your application with a single
activity and couple of fragments.
Android Studio Tools ◾ 163
The first two items on the list are generic to most other func-
tionalities that we have discussed previously. Therefore, it
is suggested to focus on fragments typical to the creation
of the Navigation component, which will help you to relate
things with what you know and avoid any confusion.
Navigation Graph
A navigation graph is a resource file that keeps all of your
destinations and actions. The graph is used to display all of
your app’s navigation paths.
Standard navigation usually consists of destinations rep-
resented by a preview thumbnail, and connecting actions
that are represented by arrows that show how users can
navigate from one destination to another.
164 ◾ Mastering Android Studio
– MyHomeFragment
– MySecondFragment
– MyThirdFragment
3. Once you are done with the defining step, you should
Add all the fragments as child elements into the
navigation parent, making sure that you are assigned
some unique id to your fragments. To illustrate with
an example4:
4 https://medium.com/@muhamed.riyas/navigation-component-the-com-
plete-guide-c51c9911684, Medium
166 ◾ Mastering Android Studio
<fragment android:id="@+id/
mySecondFragment"
android:name="com.
navigation.component.sample.
ui.fragments.MySecondFragment"
android:label="fragment_my_second"
tools:layout="@layout/
fragment_my_second">
</fragment>
<fragment android:id="@+id/
myThirdFragment"
android:name="com.
navigation.component.sample.
ui.fragments.MyThirdFragment"
android:label="fragment_my_third"
tools:layout="@layout/
fragment_my_third">
</fragment>
</navigation>
Action
As already stated, the navigation system also lets you navi-
gate via actions. In order to add action in a fragment we
can use <action/> tag inside the <fragment/> tag. At the
same time, it is possible to define more than one action
with a different id.
There are certain parameters used inside <action/>:
NavHostFragment
In order to modify your Navigations activity layouts, it has
to contain a special widget called a NavHostFragment. A
NavHostFragment interchanges different fragment desti-
nations in and out as you go through the navigation graph.
To illustrate with an example:
LinearLayout
.../>
<androidx.appcompat.widget.Toolbar
.../>
<fragment
android:layout_width=
"match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/
my_nav_host_fragment"
android:name="androidx.navigation.
fragment.NavHostFragment"
app:navGraph="@navigation/
app_navigation"
app:defaultNavHost="true"
/>
<com.google.android.material.
bottomnavigation.BottomNavigationView
NavigationController
NavController is very convenient because when you call
methods like navigate() or popBackStack(), it translates
these commands into the appropriate framework opera-
tions based on the type of destination you are navigating
to or from. For instance, when you call navigate() with an
activity destination, the NavController calls startActivity()
on your behalf.
There are few ways to insert NavigationController:
• Fragment.findNavController()
• View.findNavController()
• Activity.findNavController(viewId: Int)
view?.findViewById<Button>(R.id.button)
.setOnClickListener(View.OnClickListener {
170 ◾ Mastering Android Studio
findNavController().navigate(R.
id.action_myHomeFragment_to_
mySecondFragment)
SafeArgs
SafeArgs is another Navigation component that has a
Gradle plugin and generates simple object and builder
classes for type-safe access to arguments specified for desti-
nations and actions. For example, since we previously used
the <argument> tag for MySecondFragment, SafeArgs will
produce a class called MySecondFragmentArgs.
At the same time, SafeArgs have different parcelable
classes for arguments as well as various data types. Below
is the complete table of SafeArgs data types supported by
android (Table 4.3).
GENERATING A JAVADOC
In this last section, we shall discuss Javadoc, a helpful tool
for generating documentation directly from your Java
source files. This little part dedicated to Javadoc is only
going to cover the basic background, although it is hoped
that developers-to-be shall look for more resources and
tutorials for learning Java in order to create more sophisti-
cated Android applications.
Javadoc could also be viewed as a utility provided with
the Java SDK that allows specialists to generate code doc-
umentation from Java source files. Development envi-
ronments like Eclipse have built-in support for Javadoc
and can generate searchable HTML reference data from
Javadoc-style comments. In fact, the Android SDK refer-
ence is basically a form of Javadoc documentation.
TABLE 4.3 SafeArgs Data Types Supported by the Android Navigation Library5
Supports Null
Type app:argType Syntax Supports Default Values? Values?
Integer app:argType=“integer” Yes No
Float app:argType=“float” Yes No
Long app:argType=“long” Yes - Default values must always end with No
an “L” suffix (e.g. “123L”).
Boolean app:argType=“boolean” Yes – “true” or “false” No
String app:argType=“string” Yes Yes
Resource reference app:argType=“reference” Yes – Default values must be in the form of No
“@resourceType/resourceName” (e.g.
“@style/myCustomStyle”) or “0”
Fix a Javadoc
In case a method signature has been changed, IDE will
highlight the tag that does not match the method signa-
ture and suggest a quick fix. If you agree with it, just press
Alt+Enter to apply that fix.
You can also update an existing Javadoc comment in
order to account for the changes in the declaration using
the Fix doc comment action. For that, place the caret within
a class, method, function, or field, and press Ctrl+Shift+A.
Type fix doc comment and press Enter. Furthermore, you
can use the Fix doc comment action to add missing docu-
mentation stub with the corresponding tags: Place the caret
within a class, method, or function and invoke the action.
Render Javadocs
The android platform allows you to render Javadocs in the
editor. Typically, rendered comments are easier to read,
and they do not overload your code with extra tags.
In order to adjust the rendered view, you need to click
Toggle rendered view in the gutter next to the necessary
documentation comment (or press Ctrl+Alt+Q). Then click
Artwork Edit feature to modify the comment.
Rendered Javadocs also let you click links to go to the
referenced web pages, or view quick documentation for the
Android Studio Tools ◾ 175
Troubleshoot
Typically, the most widely known Javadoc error that
appears is Malformed locale name: en_US.UTF-8.
Thankfully, there is a pretty simple solution that one
should remember at all times. Start by clearing the Locale
field and once that is done, add -encoding utf8 -docencoding
Android Studio Tools ◾ 177
Debugging
IN THIS CHAPTER
android {
buildTypes {
customDebugType {
debuggable true
...
}
Inspect Variables
In the Debugger window, the Variables function lets you track
variables when the system stops your app on a breakpoint
and you pick a frame from the Frames pane. The Variables
pane also lets you evaluate ad hoc expressions using static
methods and variables available within the selected frame.
The Watches function provides similar capabilities
except that expressions included in the Watches func-
tion persist between debugging sessions. You should add
watches for variables and fields that you access frequently
or provide a useful state for the current debugging session.
In order to add a variable or expression to the Watches
list, follow these easy steps:
Once you start debugging, access the Watches function
and click Add. In the text box that appears, insert the name of
the variable or expression you need to watch and press Enter.
186 ◾ Mastering Android Studio
1 https://developer.android.com/studio/debug?hl=fr, Android
188 ◾ Mastering Android Studio
2 https://developer.android.com/studio/run/rundebugconfig?hl=fr, Android
Debugging ◾ 191
Symbol Directories
If you want to add symbol files to provide the debugger
with C or C++ information generated outside of Android
Studio, you can add one or more symbol directories.
Android Studio preferentially registers any files within
these directories over files generated by the Android Plugin
for Gradle. The debugger looks for symbol directories from
top to bottom, in order, until it finds what it needs. It also
searches recursively through the files in the directory. Thus,
in order to optimize the list and save your time, you can put
the directories used most often toward the top of the list.
192 ◾ Mastering Android Studio
Traceview
This tool is also deprecated. Thus, if you want to inspect.
trace files resulted from instrumenting your app with the
Debug class and recording new method traces, simply use
the Android Studio CPU profiler.
Systrace
In case you need to inspect native system processes and
forward UI jank caused by dropped frames, apply systrace
from the command line or the simplified System Trace in
the CPU Profiler.
You can use the CPU Profiler to inspect your app’s CPU
usage and thread activity in real-time while interacting
with your app, or you can review the details in recorded
method traces, function traces, and system traces.
Debugging ◾ 197
3 https://developer.android.com/studio/profile/monitor, Android
198 ◾ Mastering Android Studio
Hierarchy Viewer
Since this tool is also deprecated, you should use Layout
Inspector to inspect your app’s view hierarchy at runtime.
The Layout Inspector in Android Studio lets you com-
pare your app layout with other standard design mock-
ups, display a magnified or 3D view of your app, as well
Debugging ◾ 199
Pixel Perfect
Similar to other tools, Pixel Perfect has also been depre-
cated. If you need to work on design mockups, make sure
to use Layout Inspector.
General
1. Save all – Control+S/Command+S
2. Synchronize – Control+Alt+Y/Command+Option+Y
3. Maximize/minimize editor – Control+Shift+F12/
Control+Command+F12
4. Add to favorites – Alt+Shift+F/Option+Shift+F
4 https://developer.android.com/studio/intro/keyboard-shortcuts, Android
202 ◾ Mastering Android Studio
Viewing Layouts
1. Zoom in/out – Control+plus or Control+minus/
Command+plus or Command+minus
2. Fit to screen –Control+0/Command+0
3. Actual size – Control+Shift+1/Command+Shift+1
Writing Code
1. Generate code (getters, setters, constructors,
hashCode/equals, toString, new file, new class) –
Alt+Insert/Command+N
206 ◾ Mastering Android Studio
Debugging
1. Debug – Shift+F9/Control+D
2. Step over – F8/F8
3. Step into – F7/F7
4. Smart step into – Shift+F7/Shift+F7
5. Step out – Shift+F8/Shift+F8
6. Run to cursor – Alt+F9/Option+F9
7. Evaluate expression – Alt+F8/Option+F8
8. Resume program – F9/Command+Option+R
9. Toggle breakpoint – Control+F8/Command+F8
10. View breakpoints – Control+Shift+F8/Command+
Shift+F8
Refactoring
1. Copy – F5/F5
2. Move – F6/F6
4. Rename – Shift+F6/Shift+F6
210 ◾ Mastering Android Studio
6. Inline – Control+Alt+N/Command+Option+N
5 https://developer.android.com/studio/command-line?hl=th, Android
212 ◾ Mastering Android Studio
Compile Options
There are several key commands that you can use with the
compile command, as shown below6:
6 https://developer.android.com/studio/command-line/aapt2?hl=th, Android
214 ◾ Mastering Android Studio
Link Options
You can use the following options with the link
command7:
7 https://developer.android.com/studio/command-line/aapt2?hl=th, Android
Debugging ◾ 215
• rename-instrumentation-target-package: Changes
the name of the target package for instrumenta-
tion. It typically should be used in addition to
-rename-manifest-package.
Environment Variables
In order to specify things like where the SDK is installed
and where user-specific data is stored, you should know
how to set environment variables for Android Studio and
the command-line tools.
220 ◾ Mastering Android Studio
8 ttps://developer.android.com/studio/command-line/variables?hl=fr,
h
Android
Debugging ◾ 221
set ANDROID_SERIAL=emulator-555
adb install helloWorld.apk
set ANDROID_LOG_TAGS=ActivityManager:I
MyApp:D *:.
set ADB_TRACE=all
ADB logcat
set ANDROID_VERBOSE=socket,radio
set HTTP_PROXY=myserver:1981
export HTTP_PROXY=myserver:1981
A Ahead-of-Time (AOT)
compilation, 29
aapt2, 212, 213
Android Action Bar, 89
AAR file, see Android Archive
Android App Development, 234
file
Android application package
ABI, see Android Binary
(APK), 46, 54, 55, 182,
Interfaces; Application
235
Binary Interface
Android app modules, 8, 62
Action, 167
Android Archive (AAR) file, 63
Action Bar, 89, 90, 91
Android Beta Version 1.0, 21
hiding, 93–94
Android Binary Interfaces
overlaying, 94–95
(ABIs), 192
splitting, 92–93
Android Debug Bridge (ADB),
ADB, see Android Debug Bridge
141–143, 196, 212
Adb environment variables, 223
Android Developer Tools (ADT),
ADB Logcat environment
2, 31
variables, 223–224
Android Development, 233, 236
ADB_TRACE, 224
Android Development Kit
ADK, see Android Development
(ADK), 3
Kit
Android Device Monitor (ADM),
ADM, see Android Device
6, 140, 194, 233
Monitor
Dalvik Debug Monitor Server
ADT, see Android Developer
(DDMS), 195–196
Tools
Hierarchy Viewer, 198–199
Advantages of Android
Network Traffic tool, 199–201
development, 25
Pixel Perfect, 199
237
238 ◾ Index
J L
JAR file, see Java Archive file labelPosition, 127
Java, 2, 3, 4, 18, 25, 28, 31, 234 Layout Editor, 204–205
Java Archive (JAR) file, 42, 50 Layout Inspector in Android
Java Development Kit (JDK), 3, Studio, 198–199
38, 44–45 Layouts, 95, 118
Javadoc, generating, 170 position, 96–97
automatic comments, shortcuts and button
disabling, 174 techniques, 204
context actions, adding a types of Android Layout,
Javadoc using, 173–174 98–99
Index ◾ 243
X Y
XML file, User Interface (UI) Your Virtual Devices page, 152,
elements in, 99 153, 154
<include> tag, using, 106–107
inspecting the layout, 102
Z
lint tool, 103–104
<merge> tag, using, 107–108 Zipalign tool, 140, 212
re-usable layout, creating,
104–105
revising the layout, 102–103
XML tag, 128