1. Introduction
What you should already know
- Creating a basic Android app in Kotlin.
- Running an Android app on an emulator or on a device.
- The basics of
LinearLayout
. - Creating a simple app that uses
LinearLayout
and aTextView
.
What you'll learn
- How to work with
View
andViewGroup
. - How to arrange views in an
Activity
, usingLinearLayout.
- How to use
ScrollView
for displaying the scrollable content. - How to change the visibility of a
View
. - How to create and use string and dimension resources.
- How to create a LinearLayout using Android Studio's Layout Editor.
What you'll do
- Create the AboutMe app.
- Add a
TextView
to the layout to display your name. - Add an
ImageView.
- Add a
ScrollView
to display scrollable text.
2. App overview
In the AboutMe app, you can showcase interesting facts about yourself, or you can customize the app for a friend, family member, or pet. The app displays a name, a DONE button, a star image, and some scrollable text.
3. Task: Create the AboutMe Project
In this task, you create the AboutMe Android Studio project.
- Open Android Studio, if it's not already open.
- If a project is already open in Android Studio, select File > New > New Project.
- If a project is not already open, select + Start a new Android Studio project in the Welcome to Android Studio dialog.
- In the Create New Project dialog, in the Phone and Tablet tab, select the Empty Activity template. Click Next.
- In the next Create New Project dialog, set the following parameters and click Finish.
Attribute | Value |
Application Name | AboutMe |
Company Name android |
|
Save location | Leave the default location, or change it to your preferred directory. |
Language | Kotlin |
Minimum API level | API 19: Android 4.4 (KitKat) |
This project will support instant apps | Leave this checkbox cleared. |
Use AndroidX artifacts | Select this checkbox. |
Android Studio will take a moment to generate the project files.
- Run your app. You will see the string "Hello World" on the blank screen.
The Empty Activity template creates a single empty activity, Mainactivity.kt
. The template also creates a layout file called activity_main.xml
. The layout file has ConstraintLayout
as its root ViewGroup
, and it has a single TextView
as its content.
4. Task: Change the root layout to use LinearLayout
In this task, you change the generated root ViewGroup
to a LinearLayout
. You also arrange the UI elements vertically.
View groups
A ViewGroup
is a view that can contain child views, which are other views and view groups. Views that make up a layout are organized as a hierarchy of views with a view group as the root.
In a LinearLayout
view group, the UI elements are arranged either horizontally or vertically.
Change the root layout so that it uses a LinearLayout
view group:
- Select the Project > Android pane. In the
app/res/layout
folder, open theactivity_main.xml
file. - Select the Text tab and change the root view group from
ConstraintLayout
toLinearLayout
. - Remove the
TextView
. In theLinearLayout
element, add theandroid:orientation
attribute and set it tovertical
.
Before:
<androidx.constraintlayout.widget.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" />
</androidx.constraintlayout.widget.ConstraintLayout>
After:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
</LinearLayout>
5. Task: Add a TextView using Layout Editor
The Layout Editor is a visual-design tool inside Android Studio. Instead of writing XML code by hand to build your app's layout, you can use the Layout Editor to drag UI elements into the design editor.
To see the Layout Editor, click the Design tab. The screenshot below shows the parts of the Layout Editor.
Design editor: Displays a visual representation of your screen layout in design view, blueprint view, or both. The design editor is the main part of the Layout Editor.
Toolbar: Provides buttons to configure your layout's appearance in the design editor, and to change some layout attributes. For example, to change the display of your layout in the design editor, use the Select Design Surface
drop-down menu:
- Use Design for a real-world preview of your layout.
- Use Blueprint to see only outlines for each view.
- Use Design + Blueprint to see both displays side by side.
Palette: Provides a list of views and view groups that you can drag into your layout or into the Component Tree pane.
Attributes: Shows attributes for the currently selected view or view group. To toggle between a complete list of attributes and commonly used attributes, use the
icon at the top of the pane.
Component Tree: Displays the layout hierarchy as a tree of views. The Component Tree is useful when you have small, hidden, or overlapping views that you could not otherwise select in the design editor.
Step 1: Add a TextView
- Open the
res/layout/activity_main.xml
file, if it's not already open. - Switch to the Text tab
and inspect the code. The code has a
LinearLayout
as its root view group. (View groups are views that contain other views.)
The LinearLayout
has the required attributes layout_height
, layout_width
, and orientation
, which is vertical
by default. 3. Switch to the Design tab to open the Layout Editor.
- Drag a text view from the Palette pane onto the design editor.
- Notice the Component Tree pane. The new text view is placed as a child element of the parent view group, which is the
LinearLayout
.
- Open the Attributes pane, if it's not open already. (To open the pane, double-click the newly added
TextView
in the design editor.) - Set the following attributes in the Attributes pane:
Attribute | Value |
ID |
|
text | Set it to your name. (One of the text fields shows a wrench icon to indicate that it's for the |
textAppearance > textSize |
|
textAppearance > textColor |
|
textAppearance > textAlignment | Center |
Step 2: Create a string resource
In the Component Tree, next to the TextView,
you will notice a warning icon . To see the warning text, click the icon or point to it, as shown in the screenshot below.
To resolve the warning, create a string resource:
- In the Attributes pane, click the three dots next to the text attribute that you set to your name. The resource editor opens.
- In the Resources dialog, select Add new resource > New string Value.
- In the New String Value Resource dialog, set the Resource name field to
name
. Set the Resource value field to your own name. Click OK. Notice that the warning is gone.
- Open the
res/values/strings.xml
file and look for the newly created string resource calledname
.
<string name="name">Aleks Haecky</string>
Step 3: Create a dimension resource
You just added a resource using the resource editor. You can also extract resources in the XML code editor to create new resources:
- In the
activity_main.xml
file, switch to the Text tab. - On the
textSize
line, click on the number (20sp
) and typeAlt+Enter
(Option+Enter
on a Mac). Select Extract dimension resource from the popup menu. - In the Extract Resource dialog, enter
text_size
in the Resource name field. Click OK.
- Open the
res/values/dimens.xml
file to see the following generated code:
<dimen name="text_size">20sp</dimen>
- Open
MainActivity.kt
file, and look for the following code at the end of theonCreate()
function:
setContentView(R.layout.activity_main)
The setContentView()
function connects the layout file with the Activity
. The specified layout resource file is R.layout.activity_main
:
R
is a reference to the resource. It is an auto-generated class with definitions for all the resources in your app.layout.activity_main
indicates that the resource is a layout namedactivity_main
.
- Run your app. A
TextView
with your name is displayed.
6. Task: Style your TextView
When you look at your app screen, your name is pushed up against the top of the screen, so now you add padding and a margin.
Padding versus margin
Padding is the space inside the boundaries of a view or element. It is the space between the edges of the view and the view's content, as shown in the figure below.
A view's size includes its padding. The following are commonly used padding attributes:
android:padding
specifies padding for all four edges of the view.android:paddingTop
specifies padding for the top edge.android:paddingBottom
specifies padding for the bottom edge.android:paddingStart
specifies padding for the "starting" edge of the view.android:paddingEnd
specifies padding for the "ending" edge of the view.android:paddingLeft
specifies padding for the left edge.android:paddingRight
specifies padding for the right edge.
Margin is the space added outside of the view's borders. It is the space from the edge of the view to its parent, as shown in the figure above. The following are commonly used margin attributes:
android:layout_margin
specifies a margin for all four sides of the view.android:layout_marginTop
specifies extra space on the top side of this viewandroid:layout_marginBottom
specifies space outside the bottom side of this view.android:layout_marginStart
specifies space outside the "starting" side of this view.android:layout_marginEnd
specifies space on the end side of this view.android:layout_marginLeft
specifies space on the left side of this view.android:layout_marginRight
specifies space on the right side of this view.
Step 1: Add padding
To put space between your name and the top edge of the name
text view, add top padding.
- Open
activity_main.xml
file in the Design tab. - In the Component Tree or in the design editor, click the text view to open its Attributes pane.
- At the top of the Attributes pane, click the double-arrow icon
to see all the available attributes.
- Search for Padding, expand it, and click the three dots ... next to the top attribute. The Resources dialog appears.
- In the Resources dialog, select Add new resource > New dimen Value.
- In the New Dimension Value Resource dialog, create a new
dimen
resource calledsmall_padding
with a value of8dp
.
The dp abbreviation stands for density-independent. If you want a UI element to look the same size on screens with different densities, use dp as your unit of measurement. When specifying text size, however, always use sp (scalable pixels). Click OK.
Step 2: Add a margin
To move the name
text view away from the edge of the parent element, add a top margin.
- In the Attributes pane, search for "margin" to find Layout_Margin.
- Expand Layout_Margin, and click the three dots ... next to the top attribute.
- Create a new
dimen
resource calledlayout_margin
and make it16dp
. Click OK.
Step 3: Add a font
To make the name
text view look better, use the Android Roboto font. This font is part of the support library, and you add the font as a resource.
- In the Attributes pane, search for "fontFamily".
- In the fontFamily field, click the drop-down arrow, scroll to the bottom of the list, and select More Fonts.
- In the Resources dialog, search for
rob
and choose Roboto. In the Preview list, select Regular. - Select the Add font to project radio button.
- Click OK.
The res
folder now has a font
folder that contains a roboto.ttf
font file. The @font/roboto
attribute is added to your TextView
.
Step 4: Extract the style
A style is a collection of attributes that specify the appearance and format for a view. A style can include font color, font size, background color, padding, margin, and other common attributes.
You can extract the name
text view's formatting into a style and reuse the style for any number of views in your app. Reusing a style gives your app a consistent look when you have multiple views. Using styles also allows you to keep these common attributes in one location.
- Right-click the
TextView
in the Component Tree and select Refactor > Extract Style. - In the Extract Android Style dialog, clear the
layout_width
checkbox, thelayout_height
checkbox, and thetextAlignment
checkbox. These attributes are usually different for each view, so you don't want them to be part of the style. - In the Style name field, enter
NameStyle
. - Click OK.
- A style is also a resource, so the style is saved in the
res/values/
folder in astyles.xml
file. Openstyles.xml
and examine the generated code for theNameStyle
style, which will look similar to this:
<style name="NameStyle">
<item name="android:layout_marginTop">@dimen/layout_margin</item>
<item name="android:fontFamily">@font/roboto</item>
<item name="android:paddingTop">@dimen/small_padding</item>
<item name="android:textColor">@android:color/black</item>
<item name="android:textSize">@dimen/text_size</item>
</style>
- Open
activity_main.xml
and switch to the Text tab. Notice that the generated style is being used in the text view asstyle="@style/NameStyle"
. - Run the app and notice the changes in the font and the padding around your
TextView
.
7. Task: Add an ImageView
Most real-world Android apps consist of a combination of views to display images, display text, and accept input from the user in the form of text or click events. In this task, you add a view to display an image.
An ImageView
is a view for displaying image resources. For example, an ImageView
can display Bitmap
resources such as PNG, JPG, GIF, or WebP files, or it can display a Drawable
resource such as a vector drawing.
There are image resources that come with Android, such as sample icons, avatars, and backgrounds. You will add one of these resources to your app.
- Display the layout file In the Design tab, then drag an ImageView from the Palette pane to below
name_text
in the Component Tree. The Resources dialog opens. - Select Drawable if it's not already selected.
- Expand android, scroll, and select btn_star_big_on. It's the yellow star
.
- Click OK.
The star image is added to the layout below your name. Because you have a vertical LinearLayout
, views you add are vertically aligned.
- Switch to the Text tab and look at the generated
ImageView
code. The width is set tomatch_parent
, so the view will be as wide as its parent element. The height is set towrap_content
, so the view will be as tall as its content. TheImageView
references thebtn_star_big_on
drawable.
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="@android:drawable/btn_star_big_on" />
- To rename the
id
of theImageView
, right-click on"@+id/imageView"
and select Refactor > Rename. - In the Rename dialog, set the
id
to@+id/star_image
. Click Refactor.
- In the Design tab, in the Component Tree, click the warning icon
next to
star_image
. The warning is for a missingcontentDescription
, which screen readers use to describe images to the user. - In the Attributes pane, click the three dots ... next to the
contentDescription
attribute. The Resources dialog opens. - In the Resources dialog, select Add new resource > New string Value. Set the Resource name field to
yellow_star
, and set the Resource value field toYellow star
. Click OK. - Use the Attributes pane to add a top margin of
16dp
(which is@dimen/layout_margin
) to theyellow_star
, to separate the star image from the name. - Run your app. Your name and the star image are displayed in your app's UI.
8. Task: Add a ScrollView
A ScrollView
is a view group that allows the view hierarchy placed within it to be scrolled. A scroll view can contain only one other view, or view group, as a child. The child view is commonly a LinearLayout
. Inside a LinearLayout
, you can add other views.
The following image shows an example of a ScrollView
that contains a LinearLayout
that contains several other views.
In this task, you will add a ScrollView
that allows the user to scroll a text view that displays a brief biography. If you are only making one view scrollable, you can put the view directly into the ScrollView
, which is what you do in this task.
Step 1: Add a ScrollView that contains a TextView
- Open the
activity_main.xml
file in the Design tab. - Drag a scroll view into the layout by dragging it into the design editor, or into the Component Tree. Put the scroll view below the star image.
- Switch to the Text tab to inspect the generated code.
// Auto generated code
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
The height and width of the ScrollView
match the parent element. Once the name_text
text view and the star_image
image view have used enough vertical space to display their contents, the Android system lays out the ScrollView
to fill the rest of the available space on the screen.
- Add an
id
to theScrollView
and call itbio_scroll
. Adding anid
to theScrollView
gives the Android system a handle for the view so that when the user rotates the device, the system preserves the scroll position. - Inside the
ScrollView
, remove theLinearLayout
code, because your app will only have one view that's scrollable—aTextView
. - Drag a
TextView
from the Palette to the Component Tree. Put theTextView
under thebio_scroll
, as a child element ofbio_scroll
.
- Set the id of the new text view to
bio_text
. - Next you add a style for the new text view. In the Attributes pane, click the three dots ... next to the style attribute to open the Resources dialog.
- In the Resources dialog, search for
NameStyle
. SelectNameStyle
from the list, and click OK. The text view now uses theNameStyle
style, which you created in a prior task.
Step 2: Add your biography to the new TextView
- Open
strings.xml
, create a string resource calledbio
, and put in some long text about yourself, or about anything that you want.
Here is a sample biography:
<string name="bio">Hi, my name is Aleks.
\n\nI love fish.
\n\nThe kind that is alive and swims around in an aquarium or river, or a lake, and definitely the ocean.
\nFun fact is that I have several aquariums and also a river.
\n\nI like eating fish, too. Raw fish. Grilled fish. Smoked fish. Poached fish - not so much.
\nAnd sometimes I even go fishing.
\nAnd even less sometimes, I actually catch something.
\n\nOnce, when I was camping in Canada, and very hungry, I even caught a large salmon with my hands.
\n\nI\'ll be happy to teach you how to make your own aquarium.
\nYou should ask someone else about fishing, though.\n\n</string>
- In the
bio_text
text view, set the value of thetext
attribute to thebio
string resource that contains your biography. - To make the
bio_text
text easier to read, add spacing between the lines. Use thelineSpacingMultiplier
attribute, and give it a value of1.2
.
- Notice how in the design editor, the
bio
text runs all the way to the side edges of the screen. To fix this problem, you can add left, start, right, and end padding attributes to the rootLinearLayout
. You do not need to add bottom padding, because text that runs right up to the bottom signals to the user that the text is scrollable. - Add start and end padding of
16dp
to the rootLinearLayout
. - Switch to the Text tab, extract the dimension resource, and name it
layout_padding
.
- Run your app and scroll through the text.
Congratulations!
You have created a complete app from scratch, and it looks great!
9. Solution code
Android Studio project: AboutMe
10. Coding challenge
Inside the ScrollView
, add an ImageView
above the TextView
. When you run the app, this image, unlike the star, scrolls out of view as the text scrolls up.
Hint: The scroll view can only have one child view. You have to wrap the two scrollable views, the ImageView
and the TextView
, into a LinearLayout
.
11. Summary
- A
ViewGroup
is a view that can contain other views.LinearLayout
andScrollView
are view groups. LinearLayout
is a view group that arranges its child views horizontally or vertically.- Use a
ScrollView
when you need to display content on the screen, such as long text or a collection of images. A scroll view can contain only one child view. If you want to scroll more than one view, then add aViewGroup
such as aLinearLayout
to theScrollView
, and put the views to be scrolled inside thatViewGroup
. - The Layout Editor is a visual design editor inside Android Studio. You can use the Layout Editor to build your app's layout by dragging UI elements into the layout.
- A style is a collection of attributes that specify the appearance for a view. For example, a style can specify font color, font size, background color, padding, and margin.
- You can extract and collect all the formatting of a view into a style. To give your app a consistent look, reuse the style for other views.
12. Learn more
Udacity course:
Android developer documentation:
13. Homework
This section lists possible homework assignments for students who are working through this codelab as part of a course led by an instructor. It's up to the instructor to do the following:
- Assign homework if required.
- Communicate to students how to submit homework assignments.
- Grade the homework assignments.
Instructors can use these suggestions as little or as much as they want, and should feel free to assign any other homework they feel is appropriate.
If you're working through this codelab on your own, feel free to use these homework assignments to test your knowledge.
Answer these questions
Question 1
Which of the following is a view group?
▢ EditText
▢ LinearLayout
▢ TextView
▢ Button
Question 2
Which of the following listed view hierarchies is not valid?
▢ LinearLayout
> TextView
, TextView
, ImageView
▢ ScrollView
> LinearLayout
> TextView
, Button
, Button
, ScrollView
> TextView
▢ TextView
> TextView
, ImageView
, ScrollView
Question 3
Styles are resources defined in styles.xml
. Using styles, you can define colors, fonts, text size, and many other characteristics of a view. True or false?
▢ True
▢ False
Question 4
A ScrollView
is a view group that can contain any number of views or view groups as its children. True or false?
▢ True
▢ False
Question 5
Which UI element can be used to display images in your app?
▢ TextView
▢ ImageView
▢ Button
▢ ScrollView
14. Next codelab
For links to other codelabs in this course, see the Android Kotlin Fundamentals codelabs landing page.