0% found this document useful (0 votes)
15 views10 pages

Activities and Layouts: Application Entry Point

Chapter 10 discusses the essential components of an Android application, including the Activity class, layout files, and the AndroidManifest file, which collectively serve as the entry point for the app. It explains the Activity lifecycle, the structure of layout files in XML, and the distinction between View and ViewGroup objects, along with various layout managers available in the Android SDK. The chapter concludes with a summary of key concepts and a preview of topics to be covered in the next chapter.

Uploaded by

afeenaks894
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views10 pages

Activities and Layouts: Application Entry Point

Chapter 10 discusses the essential components of an Android application, including the Activity class, layout files, and the AndroidManifest file, which collectively serve as the entry point for the app. It explains the Activity lifecycle, the structure of layout files in XML, and the distinction between View and ViewGroup objects, along with various layout managers available in the Android SDK. The chapter concludes with a summary of key concepts and a preview of topics to be covered in the next chapter.

Uploaded by

afeenaks894
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

CHAPTER 10

Activities and Layouts


What we’ll cover:
• Activities and layouts
• View and ViewGroup objects

• Activity lifecycle
• Kotlin Android Extension

Most programs need an entry point or a beginning routine where all execution
begins. Even the simple “Hello World” in previous examples required a main function
as an entry point. Android programs are the same, it also needs its own version of the
“function main.” But the entry point of an Android program isn’t just a function called
“main”—it’s a bit more involved than that. In this chapter, we’ll explore the structure of
a basic app. We’ll take a look at how to build a user interfaces and discover what makes
them tick.

Application Entry Point


A simple app that shows a screen to the user requires at least three things. It needs (1)
an Activity class that acts as the main program file; (2) a layout file that contains all UI
definitions; and (3) a Manifest file, which ties all the project’s contents together. If you
still remember working with JavaBean’s manifest file, the Android manifest is a bit like
that. It describes the contents of the project.
When an application is launched, the Android runtime creates an Intent object and
inspects the manifest file. It’s looking for a specific value of the intent-filter node;
the runtime is trying to see if the application has a defined entry point, something like a
“main function.” Listing 10-1 shows an excerpt from a manifest file.

197
© Ted Hagos 2018
T. Hagos, Learn Android Studio 3 with Kotlin, https://doi.org/10.1007/978-1-4842-3907-0_10
Chapter 10 Activities and Layouts

Listing 10-1. Excerpt from AndroidManifest.xml


<activity android:name=".MainActivity">
<intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Listing 10-1 shows the declaration for one Activity. If the app has more than one
activity, you will see several definitions like Listing 10-1—one for each Activity. The first
line of the definition has an attribute called android:name. This attribute points to the
class name of an Activity. In this example, the name of the class is “MainActivity.”
The second line declares the intent-filter; when you see something like android.
intent.action.MAIN, on the intent-filter node, it means the Activity is the entry point for
the application. When the app is launched, this is the Activity that will interact with the user.

A
 ctivity Class
The main Activity class is responsible for the initial interaction with the user. This is a
Kotlin class, and in it, we can, and often, do the following:

• Choose which UI file to use. When we call the setLayout(xml:file)


function from inside the Activity, it will bind the Activity to xml:file.
This is called “Layout binding.” When the Activity binds to the layout,
the screen will be filled with user interface elements that users can
touch or swipe.

• Get references to view objects. View objects are also called widgets
or controls. When we have a programmatic reference to the view
objects, we can manipulate them, change their properties, or
associate them with an event. This is called View binding.
The Activity class inherits from android.app.Activity in one way or another. In our
examples, they inherit from AppCompatActivity; this is a child of FragmentActivity,
which in turn is a child of android.app.Activity. We use the AppCompatActivity class so
we can put modern UI elements like ToolBars in our project, and still run them on older
versions of Android where ToolBars are otherwise unsupported—hence, the “Compat”
in the name AppCompatActivity.
198
Chapter 10 Activities and Layouts

When the runtime launches an app that eventually launches an Activity, it creates
and tracks what’s happening to the Activity. Each Activity has a very thorough life cycle,
and each life cycle event has an associated function that we can use to customize the
behavior of the application.
Figure 10-1 shows the stages of the Activity’s life cycle. Each box shows the state
of the Activity on a particular stage of existence. The name of the function calls are
embedded in the directional arrows that connect the stages.

Figure 10-1. Activity Life Cycle

When the runtime launches the app, it calls the onCreate() function of the main
Activity, which brings the state of the Activity to “created.” You can use this function to
perform initialization routines like preparing event handling codes, etc.
The Activity will proceed to the next state, which is “started”; the Activity is visible to
the user at this point, but it’s not yet ready for interaction. The next state is “resumed”;
this is the state where the app is interacting with the user.
If the user clicks on anything that may launch another Activity, the runtime will
pause the current Activity and it will enter the “paused” state. From there, if the user goes
back to the Activity, the onResume() function is called and the Activity is running again.
On the other hand, if the user decides to open a different application, the runtime may
“stop” and eventually “destroy” the application.

199
Chapter 10 Activities and Layouts

L ayout File
A layout file contains view objects that are arranged in an XML hierarchy. The user
interface elements like buttons or text fields are written inside an XML file. Some people
may cringe at the thought of composing the UI by hand using only an XML editor. But
you don’t have to worry because AS3 makes it easy to compose user interfaces. We can
work with the layout file either in text mode (hand editing the XML), or we can work with
it in design mode (WYSIWYG).
Figure 10-2 shows a layout file displayed in two possible modes: text mode and
design mode. You can switch the modes by clicking on the tabs “Text” or “Design” on the
left lower part of the main editor window. When you change an element by editing the
XML, AS3 automatically updates the rendition of the design view. Similarly, when you
make a change in the design view, the XML file gets updated.

shown in design
shown as t ex t
mode

You can view t he layout file in t ex t or design


view by click ing t hese t abs in t he I DE

Figure 10-2. Layout file shown in both text and design mode

200
Chapter 10 Activities and Layouts

Listing 10-2 shows a typical layout file. It’s what the project creation wizard will
produce if you chose to create an “empty” activity.

Listing 10-2. activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android=http://schemas.
android.com/apk/res/android
  xmlns:app=http://schemas.android.com/apk/res-auto
  xmlns:tools=http://schemas.android.com/tools
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity">

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

A simple layout file generally has two parts: a declaration of a container and the
declarations of each UI element inside of it. In Listing 10-2, the second line (which is also
the root of the XML document) is the container’s declaration. The TextView element is
declared as a child node of the container. This is how containers and UI elements are
arranged in a layout file.

View and ViewGroup Objects


A view object is a composition unit. You build a UI by arranging one or more view objects
alongside each other, or sometimes embedded in each other. There are two kinds of
views as the Android library defines it, a “view” and a “view group.” An example of a View
object is a button or a text field. These objects are meant to be composed alongside other
views, but they are not meant to contain child views—they are meant to stand alone.

201
Chapter 10 Activities and Layouts

A ViewGroup, on the other hand, can contain child views—it’s the reason why they’re
sometimes called containers.
Figure 10-3 shows the class hierarchy of some of the more common UI elements.
Every item in a user interface is a child of the android.view.View class. We can use pre-­
built user interface elements in the Android SDK such as TextView, Button, ProgressBars,
etc., or, if need be, we can construct custom controls (widgets or views are sometime
called “controls”) by either (1) sub-classing existing elements like TextViews; (2)
subclassing the View class itself and completely drawing a custom widget from scratch;
or (3) sub-classing the ViewGroup and embedding other widgets in it—this is known as a
composite view (the RadioGroup in Figure 10-3 is an example of such).

Figure 10-3. ViewGroup class hierarchy

Each view object ultimately becomes a Java object at runtime, but we work with
them as XML elements during design time. We don’t have to worry about how Android
inflates the XML into Java objects because that process is invisible to us—it happens
behind the scenes. Figure 10-4 shows a logical representation of Android’s compilation
process.

202
Chapter 10 Activities and Layouts

Figure 10-4. Android compilation process

The Kotlin compiler transforms the program source files into Java byte codes. The
resulting byte codes are combined with the Kotlin Standard Library to form a DEX file.
A DEX file is a Dalvik Executable—it’s the executable format that the Android Runtime
(ART) understands. Before the dex files and other resources gets wrapped into an
Android package (APK), it also produces as a side effect a special file named “R.class.”
We use the R.class to get a program reference to the UI elements that we defined in the
layout file.

Containers
Apart from creating composite views, the ViewGroup class has another use. They form
as the basis for layout managers. A layout manager is a container that’s responsible for
controlling how child views are positioned on the screen, relative to the container and to
each other. Android comes with a couple of pre-built layout managers. Table 10-1 shows
us some of them.

203
Chapter 10 Activities and Layouts

Table 10-1. Layout Managers


Layout Manager Description

LinearLayout positions the widgets in single row or column, depending on the selected
orientation. Each widget can be assigned a weight value that determines the
amount of space the widget occupies compared to the other widgets.
TableLayout arranges the widgets in a grid format of rows and columns
FrameLayout stacks child views on top of each other. The last entry on the XML layout file is
the one on top of the stack.
RelativeLayout Views are positioned relative to other views and the container by specifying
alignments and margins on each view.
ConstraintLayout The ConstraintLayout is the newest layout. It also positions widgets relative to
each other and the container (like RelativeLayout). But it accomplishes the layout
management by using more than just alignments and margins. It introduces the
idea of a “constraint” object which anchors a widget to target. This target could
be another widget or a container; or another anchor point. This is the layout we
will use for most of our examples in this book.

Now that we have some working knowledge about activities and layouts, let’s explore
them at the code level in the next section.

H
 ello World
Let’s create a new application with an empty activity. If you want to follow along and
work on the code examples, the project information is shown in Table 10-2.

204
Chapter 10 Activities and Layouts

Figure 10-15. CH10Hello running on an emulator

Chapter Summary
• The entry point for an Android application requires three files: the
manifest file, the layout file, and an Activity class
• The AndroidManifest file declares all the contents of the Android
project. The manifest may be able to designate an Activity class that
will serve as the application’s entry point.
• A layout file describes the UI structure of a screen. Each element
is described as an XML node, but the XML file is inflated
during runtime. The inflation process produces the Java object
representations of the UI elements.

• All UI elements inherits from the android.view.View class.

• Composite views can be constructed by inheriting from the


ViewGroup class.

218
Chapter 10 Activities and Layouts

• Layout managers provide ways to arrange UI elements in a screen.


The Android SDK has plenty of pre-built managers we can use out of
the box.

• The Kotlin Android Extensions allow us to simplify view-binding


codes by exposing the properties and functions of view elements. We
don’t need to use findViewById anymore.
In the next chapter, we’ll learn how to:
• Work with some basic View elements like Buttons and Toasts
• Use Kotlin’s Android Extensions to get references to View objects; it
replaces ButterKnife

• Handle clicks and long clicks; we’ll do both long-form using the full
syntax of object expressions and the short-cut way using lambda
expressions

219

You might also like