Codecademy Logo

Building Android Apps

Top Level Components

The ability to text, email, play games and much more are accomplished in Android applications through four top-level component classes: BroadcastReceiver, ContentProvider, Service, and Activity. These are all represented by Java Objects.

A diagram of the four top-level component classes of an Android application. 

The illustration is labeled 'Application Components'. Under the label there is a long rectangle with rounded corners whose border is a dotted yellow line. Below the bottom border of the rectangle there are four labels for the application components. These four labels are 'Service', 'Receiver', 'Provider', and 'Activity'.  Each component also has an illustration displayed within the long rectangle to symbolize it.

The left-most component illustration contained in the rectangle is for 'Servce', it is a cog shape. In the center of the cog shape there is an opening and closing angle bracket and a forward slash between the brackets. 
The next component illustration, to the right is for 'Receiver'. This illustration displays an ear with lines near the ear to indicate sound.

The third illlustration is for the 'Provider' component. It is three blue squares, with a gray dot in the center of each square, connected to a yellow box with gray lines.

The last, right-most, illustration in the rectangle is for 'Activity' and displays a hand using a touch gesture on a device.

Behind the middle two components there is a faint illustration of a game console controller.

Activity Components

Activities provide the most visible of the application components. They present content to the screen and respond to user interaction. Activity components are the only components that present interactive content to the user. An Activity represents something an application can do, and an application often “does” several things – meaning, most applications provide more than one Activity.

A diagram representing several different Activity components. The diagram is labeled 'Activity'. There are three illustrations in the diagram with labels under each illustration. Between the illustrations there are white arrows (with a dotted line) pointing to the right. The three labels are 'Load Layout', 'Inflate Views And ViewGroups', and 'Present to User'.

On the left side of the diagram there is an illustration of a simple layout with a light gray background and empty blue rectangles. Under the illustration there is a label, 'Load Layout'. The word 'Layout' is highlighted with red text. 

The middle illustration has three blue rectangles in a vertical stack. Attached to the left side of the top rectangle, there is a purple arrow pointing right. On the right side of the top rectangle the line for the arrow continues in an arch shape to the right side of the middle rectangle. The arrow continues from the left side of the middle rectangle in an arch shape to the left side of the bottom rectangle. The purple arrow continues out of the right side of the last rectangle, with the arrow head pointing right.  The middle illustration is labeled 'Inflate Views And ViewGroups', the words 'Views' and 'View' are highlighted with green text, and the word 'Groups' is highlighted with pink text.

On the right side of the diagram there is an illustration of a user's hand interacting with the application. Under this last illustration there is the label 'Present to User'.

Android Views

In Android, Views are atomic, indivisible elements that draw themselves to the screen. They can display images, text, and more. Like periodic elements combine to form chemicals, we combine Views to form design components that serve a purpose to the user.

A simple illustration of the periodic table. There is text under the table, '(Periodic Table)', with an arrow from the right side of the text curving up to the left to point at the periodic table. The periodic table has minimal detail, no text, and has a partial (not exact) grid drawn of the table. The grid's columns are rainbow colored, for example the first column is red and the second is orange. The bottom grid of the periodic table illustration is pink.

Android ViewGroups

In Android, ViewGroups arrange Views (and other ViewGroups) to form meaningful designs. ViewGroups are the special bond that combines Views to form design components that serve a purpose to the user. ViewGroups are Views that may contain other Views within them.

An example ViewGroup. There are various labels around the ViewGroup for the items inside the ViewGroup. The labels are color coded, the words 'Image' and 'Text' are white, the word 'View' is green, and the word 'Group' is pink.

There is a large rectangle with a pink border that is labeled 'ViewGroup'. Inside the pink rectangle there is an image, which is a white line drawing, of a goat and mountains labeled 'ImageView'. Under the image in the lower left corner of the pink rectangle, there is a green dotted rectangle with an avatar illustration in white. This rectangle is labeled as 'ImageView'. To the right of the avatar there are two long rectangles each with a green dotted border and white text inside. The top rectangle has the text 'Best Goat Video Evar!' in white bold letters. The bottom rectangle has the text 'goatfanz - 2 gajillion views' in white. Each of these two rectangles that contain text are labeled 'TextView'.

Android Layout Files

In Android, each layout is represented by an XML file. These plain text files serve as blueprints for the interface that our application presents to the user.

<ConstratinLayout ...>
<ImageView id="thumbnail" .../>
<ImageView id="avatar" .../>
<ImageView id="title" .../>
<imageView id="subtitle" .../>
</ConstratinLayout>

Layout File Conversion

When Activities first launch, they read a layout file and convert it to a set of corresponding Java objects. These objects inherit from the base View object, and may draw themselves to the screen.

A diagram of layout file conversion. There are three illustrations in the diagram with labels under each illustration. Between the illustrations there are white arrows (with a dotted line) pointing to the right. The three labels are 'Load Layout', 'Inflate Views And ViewGroups', and 'Present to User'.

On the left side of the diagram there is an illustration of a simple layout with a light gray background and empty blue rectangles. Under the illustration is the label, 'Load Layout'. The word 'Layout' is highlighted with red text. 

The middle illustration has three blue rectangles in a vertical stack. Attached to the left side of the top rectangle, there is a purple arrow pointing right. On the right side of the top rectangle the line for the arrow continues in an arch shape to the right side of the middle rectangle. The arrow continues from the left side of the middle rectangle in an arch shape to the left side of the bottom rectangle. The purple arrow continues out of the right side of the last rectangle, with the arrow head pointing right.  The middle illustration is labeled 'Inflate Views And ViewGroups', the words 'Views' and 'View' are highlighted with green text, and the word 'Groups' is highlighted with pink text.

On the right side of the diagram there is an illustration of a user's hand interacting with the application. Under this last illustration there is the label 'Present to User' in white text.

Project Files

Android project files belong to one of three main categories: configuration, code, and resource. Configuration files define the project structure, code files provide the logic, and resource files are pretty much everything else.

An example of Android project files in the project navigation panel of the Android Studio editor. 

The root directory contains an 'app' folder and a 'Gradle Scripts' folder. 

The 'app' folder has a 'manifests' folder, a 'java' folder, a generated 'java' folder, and a 'res' folder. 

The 'Gradle Scripts' directory contains 7 items: a 'build.gradle (Project: My Application)' file, a 'build.gradle (Module: app)' file, a gradle-wrapper.properties (Gradle Version) file, a 'proguard-rules.pro (ProGuard Rules for ":app")' file, a 'gradle.properties' (Project Properties)' file, a 'settings.gradle (Project Settings)' file, and a 'local.properties (SDK Location)' file. 

The project navigation panel has icons to the left of the folders and files. The folders and the 'Gradle Scripts' directory have expand/collapse arrows to the left of the folder names. The folders also have folder icons to the right of the arrows (left of the labels). The generated java folder has a black and white circular icon at the bottom right of its folder icon that looks like a fan/pinwheel/windmill. The 'res' (resources) folder also has an icon at the bottom right of its folder icon that is a stack of four orange rectangles. The 'Gradle Scripts' directory has a Gradle icon (an elephant) to the right of the expanded arrow.  

The '.gradle' files all have the Gradle elephant icon to the left of the file names. The '.properties' files have a properties file icon (a dog eared paper icon with three small bars next to each other at the bottom right corner of the file icon. These bars grow in height and follow the color pattern: red, yellow, green from left to right. The 'proguard-rules.pro' file has a dog-eared paper icon with three lines in the center of the paper icon.

In the project navigation panel there are three boxes highlighted with a thick pink outline around some of  the various files and folders. The first box contains the 'java' and 'java (generated)' folders. The second box outlines the 'res' folder. The third box outlines all the files that are in the 'Gradle Scripts' folder.

Layout Editor

The Android Studio Layout Editor includes two tabs: Text and Design. The Text tab edits the underlying XML file directly, and the Design tab provides a drag-and-drop interface for achieving the same results.

An example XML file open in the Android Studio Layout Editor with the 'Text' tab selected.

The XML file that is open in the Android Studio Layout Editor is named 'activity_main.xml'. In the editor, the file name is in the top left corner and has a code file icon on the left of the file name and a close, 'X', icon on the right of the file name.

In the open file there are numbered lines on the left of the editor (1-18). These line numbers are on a light gray background and the font color is dark gray. There is a dividing line between the line numbers and the text (XML) of the file. The text of the XML file is on a white background. At the bottom of the text editor there is a 'Design' and 'Text' tab, and the 'Text' tab is selected.

The XML file has a parent layout, '<androididx.constraintlayout.widget.ConstraintLayout>', with various attribute values set. Nested within the parent, there is a single '<TextView>' class which also has various attribute values set.

Mandatory Layout Attributes

In Android, two attributes are mandatory within every layout: layout_width and layout_height, and the most common values for these attributes are match_parent and wrap_content.

An example portion of the Android Studio design editor that has two views, and the declared attributes for one of the views.

In the design editor at the top left, there is a layout editor toolbar that contains the selected device size and type (Pixel for this example), the Android API version (28), the app theme (AppTheme), and the selected language (Default). Under the layout editor toolbar there is another toolbar with tools to adjust the views in the layout. On the top right of the design editor, in the layout editor toolbar, there are zoom controls, a maximize editor button, and an error notification icon. 

In the design editor there are two views, a text view that has the text 'Hello World!', and below the text there is a button view with the text 'button' in all capital letters. In the editor the button view is selected and highlighted with a blue border. 

To the right of the design editor, there is an edit attributes panel labeled 'Attributes'. At the top right of the panel there is a search icon, a settings (cog) icon, and a minimize panel icon. The title of the view (button) is on the left under the attributes panel label and the title is also on the right side under the search/settings/minimize icons. Under the title of the view there is an 'id' field with the value 'button'.

Under the id field there is a panel labeled 'Declared Attributes' on the left, and a plus and minus icon to the right of the label. The declared attributes panel is expanded to list attributes specified in the layout file which include a 'layout_width' set to 'match_parent', a 'layout_height' attribute set to 'wrap_content', an 'id' attribute set to 'button', and a 'text' attribute set to 'Button'. The value for the 'text' attribute has an orange border. To the right of the 'layout_width' and 'layout_height' attributes there are dropdown arrows pointing down, and to the right of the arrows there are vertical capsule shapes outlined in dark gray. The 'text' attribute also has the vertical capsule shape outlined in dark gray to the right of the attribute value.

Constraint Layout

ConstraintLayout arranges its children relative to itself and other children (leftOf, rightOf, below, etc.). It is more complex than a linear or frame layout, but it’s a lot more flexible. It’s also much more efficient for complex UIs as it gives you a flatter view hierarchy, which means that Android has less processing to do at runtime. Another advantage of using constraint layouts is that they’re specifically designed to work with Android Studio’s design editor. Unlike linear and form layouts where you usually make changes to XML, you build constraint layouts visually. You drag and drop GUI components onto the design editor’s blueprint tool, and give it instructions for how each view should be displayed.

Linear Layout

In Android, LinearLayout arranges its children in a straight line, either horizontally or vertically. If it is vertically, they’re displayed in a single column, and if it’s horizontally, they’re displayed in a single row.

Linear and Constraint Layouts

LinearLayout is ‘top-down’ and dictates the final position to each child, whereas ConstraintLayout is primarily ‘bottom-up,’ as it requires its children to supply position-related attributes.

Children of ConstraintLayout

Children of ConstraintLayout must provide one horizontal and one vertical constraint to define their position within the ConstraintLayout. Android Studio will warn us if we have set neither vertical nor horizontal constraints for any child component of a ConstraintLayout.

An example of Android Studio's warnings provided after not setting horizontal and vertical constraints.

At the top of the example there is the word 'Constraints' with a down pointing arrow icon to the left of the word. Under the word 'Constraints' there is the text 'Not Horizontally Constrained' that has a red circle with an exclamation point in the center to the left of the text. Under the first warning text there is the text 'Not Vertically Constrained' that has a red circle with an exclamation point in the center to the left of the text.

Create Space with Margins

Margins introduce space between Views, and Views often benefit from the “breathing room” margins provide.

An illustrated example of margins between views.

There is a rectangle outlined in red with three boxes in a horizontal line in the center. The first box on the left is outlined in green and has a smiley face in the center. The middle box is also outlined in green and has an amazed smiley face in the center. The last box on the right is outlined in green and has a squinty smiley face in the center.

The three boxes are spaced evenly in the red outlined rectangle. There is even spacing around the top bottom and sides of the boxes.

Resource Qualifiers

Resource qualifiers help us generate XML files for specific device configurations. Resource qualifiers allow us to create alternate versions of a resource tailored to one or more device factors: screen size, aspect ratio, android version, and others, such as screen orientation.

AndroidX

AndroidX is a support library designed to bring new features to old devices. AndroidX is a compatibility library that offers unique features and the latest APIs to versions of Android past & present. AndroidX enables older devices to have a taste of new APIs and Android technology.

A table listing some Android APIs and when they are available to use, based on the version of Android used.

Table title: AndroidX API Availability
Table description: Row 1, column headings: column one: API, column two: AndroidX, column three: Android v29, and column four: Android v.. (this last column heading is a placeholder for other versions of Android that are not listed in the table).

Row 2, column one (API) contains the text: ConstraintLayout. In the second column (AndroidX), there is a green check mark indicating that ConstraintLayout is available through AndroidX. Next, in the the third column (Android v29), there is a red circle with a white letter X in the center, indicating that ConstraintLayout is not available through Android v29. In the fourth and final column (Android v..), there is another red circle with a white letter X indicating that ConstraintLayout is not available through Android v.. .
Row 3, the first column (API ), contains: LinearLayout. The second column (AndroidX) contains a red circle with a white letter X noting that LinearLayout is not available through AndroidX. The last two columns (Android v29 and Android v.. respectively) both contain green checkmarks to signify that LinearLayout is available through Android v29 and Android v.. .

The fourth and final row, column one (API), contains the text: LinearLayoutCompact. The second column (AndroidX) contains a green checkmark to note that LinearLayoutCompact is available through AndroidX. The last two columns (Android v29 and Android v.. respectively) each contain a red circle with a white letter X in the center to note that LinearLayoutCompact is not available to use through Android v29 and Android v.. .

ConstraintLayout Exclusive to AndroidX

Unlike LinearLayout, available in version one of the Android development kit, ConstraintLayout is not a part of any version of Android past or present and is only available through AndroidX.

An example file creation shows that ConstraintLayout is only available through AndroidX.

The example screen (of the file creation) has the text 'New Resource File' to indicate that the file is being created. Following the 'New Resource File' text, there are fields to configure the file. These include 'File name:', 'Resource type:', 'Root element:', 'Source set:', 'Directory name:', and 'Available qualifiers:'.

For this file creation example, the file name is 'contact_card_main', the resource type is 'Layout' (this field also has a dropdown arrow on the same line), the root element is not typed into the root element field completely, but 'constraintlayout' is being typed out. The root element field is selected and has an autocomplete list to choose from with the 'constraint' keyword (from ConstraintLayout) as the basis for this list. The list includes: androidx.constraintlayout.widget.ConstraintLayout, androidx.constraintlayout.widget.Barrier, androidx.constraintlayout.widget.Constraints, androidx.constraintlayout.widget.Group, androidx.constraintlayout.widget.Guideline, and the last item in the list before the example screen is cropped, is androidx.constraintlayout.widget.Placeholder (this item has a pi symbol on the same line).

We do not know what the field values are for 'Source set:' (but, this item does have a dropdown arrow on the same line), 'Directory name:', or 'Available qualifiers:' as these field inputs are covered up by the autocomplete list from the 'Root element:' autocomplete previously mentioned. We are also not able to read any other selections such as fields or buttons that may be in this file configuration.

Android Namespaces

In Android, namespaces help avoid attribute conflicts (two versions of the src attribute on a single ImageView, for example). Three common namespaces are: android, tools, and app. The android namespace belongs to the Android SDK and represents attributes available out-of-the-box. The app namespace allows us to reference attributes defined by external libraries (e.g. AndroidX) and those defined by our application. The tools namespace allows us to define attributes used exclusively for development, the user’s device never sees these attributes.

...
xmlns:tools=""
xmlns:app=""
android:layout_height=""
...

Android Resource Identifier

For Views to relate or constrain themselves to their siblings, they need a way to reference them — resource identifiers satisfy this need.

Component Palette

The component palette provides a selection of elements that we may drag and drop right into our layout.

A list of the element selection in the Android Studio palette.

At the top left of the palette there is the word: 'Palette' as a label to or show that we have the Android Studio palette open. At the top right across from the label there is a search, a settings, and a minimize icon.

Nested under the Android Studio palette label is a list of groups of components with the labels: 'Common', 'Text', 'Buttons', 'Widgets', 'Layouts', 'Containers', 'Google', and 'Legacy'. 

The 'Common' group of elements is selected from the palette. There is a list to the right of the selected palette containing elements (and their matching icons to the left of the elements) that are commonly used when building Android applications. 

These are the elements that we are able to drag to our layout. These elements include: 
- 'TextView', with the capital letter A and the lowercase letter B as the icon.
- 'Button', which has an opaque rectangle with rounded corners as the icon.
- 'ImageView', whose icon is a rectangle containing two contrasting triangles next to each other, representing a landscape photo with mountains.
- 'RecyclerView', whose icon is a bulleted list of three lines. This element also has a download icon to the right of the label. The download icon is a down pointing arrow with a line under the arrow point.
- 'fragment', which is wrapped in an opening and closing angle bracket pair. The icon is an opening and closing angle bracket pair with nothing between the opening and closing brackets.
- 'ScrollView', whose icon is a rectangle that has a vertical, contrasting, line on the right of the rectangle to represent a scroll bar. 
- 'Switch', whose icon is a horizontal toggle that is capsule shaped. There is a circular indicator in the right most position of the toggle capsule.

Material Design IOS Android Web Applications

Google introduced Material Design in 2014 to help standardize the appearance of web and mobile applications across the Google ecosystem. Material Design continues to evolve and is available for iOS, Android, and several web frameworks—however, applying its principles is entirely optional.

Material Design Documentation

By right-clicking any element within the component palette, we may navigate to its respective documentation or Material Design guidelines.

Material Design Guidelines

The purpose and behavior of most Views, including CardView, are inspired by Material Design guidelines. Google introduced Material Design in 2014 to help standardize the appearance of web and mobile applications across the Google ecosystem.

A diagram of the Android Studio palette listing the element selections for the Containers group, with the 'CardView' component selected.

At the top left of the palette there is the word: 'Palette' as a label to show that we have the Android Studio palette open. At the top right across from the label there is a search, a settings, and a minimize icon.

Nested under the Android Studio palette label is a list of groups of components with the labels: 'Common', 'Text', 'Buttons', 'Widgets', 'Layouts', and 'Containers'.

The 'Containers' group of elements is selected from the palette, and there is a list to the right of the palette containing elements (and their matching icons to the left of the elements).

These are elements that we are able to drag to our layout. These elements include: 

- 'Spinner', with three horizontal lines, where the top line has a flag shape on the right side of the line, as the icon.

- 'RecyclerView', whose icon is a bulleted list of three, opaque, lines - this element also has a download icon to the right of the label (which is a down pointing arrow with a line under the arrow point).

- 'ScrollView', with an opaque rectangle that has a thin, contrasting, long rectangle on the right of the opaque rectangle to represent a scroll bar as the icon. 

- 'HorizontalScrollView', with an opaque rectangle that has a thin, contrasting, long rectangle on the bottom of the opaque rectangle to represent a scroll bar as the icon.

- 'NestedScrollView' which has the same icon as the 'ScrollView' and also has a download icon on the right side of the view label.

- 'ViewPager' whose icon is two rectangles that are the same height, the first rectangle contains a play (right pointing arrow) icon, and the second rectangle is not as wide as the first and is solid.

- 'CardView' that has an icon made of three stacked rectangles that are the same width, but the top and bottom rectangles are about half the height of the middle rectangle. There is also a download icon to the right of the view label. A cursor is hovering over the 'CardView' element.

Layout Inflation Process

During project creation, Android Studio associates the activity_main.xml layout file with the MainActivity object. The two are associated not by name, but by the setContentView method found in the Activity class. This complex method accepts a layout file resource identifier, generates the Views designed within, and presents them on screen — a process known as Layout Inflation

setContentView(R.layout.activity_main);

Decor View

Activity objects may opt to present nothing to the screen, but the Android operating system always provides them with a Decor View. Decor View is the top-level ViewGroup in which Activity objects draw their content.

Android FindViewById

setContentView converts all the XML components in our layout into Java View objects, so after this method returns, we can access any View object from our layout programmatically. To find a specific View object, we invoke the findViewById() method. This method returns an object that inherits from the View object, or View itself.

public class MainActivity extends AppCompatActivity {
...
setContentView(R.layout.activity_main);
findViewById(R.id.incl_cardview_contact-card_main_1);
...
}

Android Motion Event Objects

MotionEvent objects are created by Android after capturing user input from the touchscreen and translating it into operable data. All Views can respond to clicks, drags, swipes, and more by processing MotionEvents.

Clicks And Long Clicks

By default, all Views detect clicks and long-clicks.