1.3: Working with TextView Elements
Contents:
- What you should already KNOW
- What you will LEARN
- What you will DO
- App overview
- Task 1: Add several text views
- Task 2: Add active web links and a ScrollView
- Task 3: Scroll multiple elements
- Coding challenge
- Summary
- Related concept
- Learn more
The TextView class is a subclass of the View class that displays text on the screen. You can control how the text appears with TextView attributes in the XML layout file. This practical shows how to work with multiple TextView elements, including one in which the user can scroll its contents vertically.
If you have more information than fits on the device's display, you can create a scrolling view so that the user can scroll vertically by swiping up or down, or horizontally by swiping right or left.
You would typically use a scrolling view for news stories, articles, or any lengthy text that doesn't completely fit on the device display. You can also use a scrolling view to enable users to enter multiple lines of text, or to combine UI elements (such as a text field and a button) within a scrolling view.
The ScrollView class provides the layout for the scrolling view. ScrollView is a subclass of FrameLayout, and developers should place only one view as a child within it, where the child view contains the entire contents to scroll. This child view may itself be a view group (such as a layout manager like LinearLayout) with a complex hierarchy of objects. Note that complex layouts may suffer performance issues with child views such as images. A good choice for a view within a ScrollView is a LinearLayout that is arranged in a vertical orientation, presenting top-level items that the user can scroll through.
With a ScrollView, all of the views are in memory and in the view hierarchy even if they aren't displayed on screen. This makes ScrollView ideal for scrolling pages of free-form text smoothly, because the text is already in memory. However, ScrollView can use up a lot of memory, which can affect the performance of the rest of your app. To display long lists of items that users can add to, delete from, or edit, consider using a RecyclerView, which is described in a separate practical.
What you should already KNOW
From previous practicals, you should be able to:
- Create a Hello World app with Android Studio.
- Run an app on an emulator or a device.
- Implement a TextView in a layout for an app.
- Create and use string resources.
- Convert layout dimensions to resources.
What you will LEARN
You will learn to:
- Use XML code to add multiple TextView elements.
- Use XML code to define a scrolling view.
- Display free-form text with some HTML formatting tags.
- Style the TextView background color and text color.
- Include a web link in the text.
What you will DO
In this practical, you will:
- Create the Scrolling Text app.
- Add two TextView elements for the article heading and subheading.
- Use TextAppearance styles and colors for the article heading and subheading.
- Use HTML tags in the text string to control formatting.
- Use the lineSpacingExtra attribute to add line spacing for readability.
- Add a ScrollView to the layout to enable scrolling a TextView element.
- Add the autoLink attribute to enable URLs in the text to be active and clickable.
App overview
The Scrolling Text app demonstrates the ScrollView UI component. ScrollView is a view group that in this example contains a TextView. It shows a lengthy page of text—in this case, a music album review—that the user can scroll vertically to read by swiping up and down. A scroll bar appears in the right margin. The app shows how you can use text formatted with minimal HTML tags for setting text to bold or italic, and with new-line characters to separate paragraphs. You can also include active web links in the text.
In the above figure, the following appear:
- An active web link embedded in free-form text
- The scroll bar that appears when scrolling the text
Task 1: Add several text views
In this practical, you will create an Android project for the Scrolling Text app, add TextViews to the layout for an article title and subtitle, and change the existing "Hello World" TextView element to show a lengthy article. The figure below is a diagram of the layout.
You will make all these changes in the XML code and in the strings.xml file. You will edit the XML code for the layout in the Text pane, which you show by clicking the Text tab, rather than clicking the Design tab for the Design pane. Some changes to UI elements and attributes are easier to make directly in the Text pane using XML source code.
1.1 Create the project and TextView elements
In Android Studio create a new project with the following parameters:
Attribute Value Application Name Scrolling Text Company Name android.example.com (or your own domain) Phone and Tablet Minimum SDK API15: Android 4.0.3 IceCreamSandwich Template Empty Activity Generate Layout File checkbox Checked In the app > res > layout folder, open the activity_main.xml file, and click the Text tab to see the XML code if it is not already selected.
At the top, or root, of the view hierarchy is a view group such as ConstraintLayout. Change this view group to RelativeLayout. The second line of code now looks something like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
RelativeLayout allows you to position its child Views relative to each other or relative to the parent RelativeLayout itself. The default "Hello World" TextView element that is created by the Empty Layout template is a child View within the RelativeLayout view group. For more information about using a RelativeLayout, see the Relative Layout API Guide.
Add a
TextView
element above the "Hello World"TextView
. Add the following attributes to the TextView:TextView #1 attribute Value android:id "@+id/article_heading" layout_width "match_parent" layout_height "wrap_content" android:background "@color/colorPrimary" android:textColor "@android:color/white" android:padding "10dp" android:textAppearance "@android:style/TextAppearance.Large" android:textStyle "bold" android:text "Article Title" Tip: The attributes for styling the text and background are summarized in the TextView class documentation.
Extract the string resource for the
android:text
attribute's hard-coded string"Article Title"
in theTextView
to create an entry for it in strings.xml.Place the cursor on the hard-coded string, press Alt-Enter (Option-Enter on the Mac), and select Extract string resource. Then edit the resource name for the string value to article_title.
Tip: String resources are described in detail in the String Resources documentation.
Extract the dimension resource for the
android:padding
attribute's hard-coded string"10dp"
in the TextView to create an entry in dimens.xml.Place the cursor on the hard-coded string, press Alt-Enter (Option-Enter on the Mac), and select Extract dimension resource. Then edit the Resource name to padding_regular.
Add another
TextView
element above the "Hello World"TextView
and below theTextView
you created in the previous steps. Add the following attributes to theTextView
:TextView #2 Attribute Value android:id "@+id/article_subheading" layout_width "match_parent" layout_height "wrap_content" android:layout_below "@id/article_heading" android:padding "@dimen/padding_regular" android:textAppearance "@android:style/TextAppearance" android:text "Article Subtitle" Note that since you extracted the dimension resource for the
"10dp"
string to padding_regular in the previously createdTextView
, you can use"@dimen/padding_regular"
for theandroid:padding
attribute in thisTextView
.- Extract the string resource for the
android:text
attribute's hard-coded string"Article Subtitle"
in theTextView
to article_subtitle. - In the "Hello World"
TextView
element, remove thelayout_constraint
attributes, if they are present. Add the following
TextView
attributes to the "Hello World"TextView
element, and change theandroid:text
attribute:TextView Attribute Value android:id "@+id/article" android:lineSpacingExtra "5sp" android:layout_below "@id/article_subheading" android:text Change to "Article text" - Extract the string resource for
"Article text"
to article_text, and extract the dimension resource for"5sp"
to line_spacing. - Reformat and align the code by choosing Code > Reformat Code. It is a good practice to reformat and align your code so that it is easier for you and others to understand.
1.2 Add the text of the article
In a real app that accesses magazine or newspaper articles, the articles that appear would probably come from an online source through a content provider, or might be saved in advance in a database on the device.
For this practical, you will create the article as a single long string in the strings.xml resource.
- In the app > res > values folder, open strings.xml.
- Enter the values for the strings
article_title
andarticle_subtitle
with a made-up title and a subtitle for the article you are adding. The string values for each should be single-line text without HTML tags or multiple lines. Enter or copy and paste text for the
article_text
string.Use the text provided for the
article_text
string in the strings.xml file of the finished ScrollingText app, or use your own generic text. You can copy and then paste the same sentence over and over, as long as the result is a long section of text that will not fit entirely on the screen. Keep in mind the following (refer to the figure below for an example):As you enter or paste text in the strings.xml file, the text lines don't wrap around to the next line—they extend beyond the right margin. This is the correct behavior—each new line of text starting at the left margin represents an entire paragraph.
Enter \n to represent the end of a line, and another \n to represent a blank line.
Why? You need to add end-of-line characters to keep paragraphs from running into each other.
Tip: If you want to see the text wrapped in strings.xml, you can press Return to enter hard line endings, or format the text first in a text editor with hard line endings.
If you have an apostrophe (') in your text, you must escape it by preceding it with a backslash (\'). If you have a double-quote in your text, you must also escape it (\"). You must also escape any other non-ASCII characters.See the "Formatting and Styling" section of String Resources for more details.
Enter the HTML and </b> tags around words that should be in bold.
Enter the HTML and </i> tags around words that should be in italics. Note, however, that if you use curled apostrophes within an italic phrase, you should replace them with straight apostrophes.
You can combine bold and italics by combining the tags, as in ... words...</i></b>. Other HTML tags are ignored.
Enclose The entire text within
<string name="article_text"> </string>
in the strings.xml file.Include a web link to test, such as www.google.com (the example below uses
www.rockument.com
). Don't use an HTML tag—any HTML tags except the bold and italic tags will be ignored and presented as text, which is not what you want.
Run the app.
The article appears, and you can even scroll it, but the scrolling is not smooth and there is no scroll bar because you haven't yet included a ScrollView (which you will do in the next task). Note also that tapping a web link does not currently do anything. You will also fix that in the next task.
Solution code
Depending on your version of Android Studio, the activity_main.xml layout file will look something like the following:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.android.scrollingtext.MainActivity">
<TextView
android:id="@+id/article_heading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:textColor="@android:color/holo_orange_light"
android:textColorHighlight="@color/colorAccent"
android:padding="10dp"
android:textAppearance="@android:style/TextAppearance.Large"
android:textStyle="bold"
android:text="@string/article_title"/>
<TextView
android:id="@+id/article_subheading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/article_heading"
android:padding="10dp"
android:textAppearance="@android:style/TextAppearance"
android:text="@string/article_subtitle"/>
<TextView
android:id="@+id/article"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/article_subheading"
android:lineSpacingExtra="5sp"
android:text="@string/article_text"/>
</RelativeLayout>
Task 2: Add active Web links and a ScrollView
In the previous task you created the Scrolling Text app with TextViews for an article title, subtitle, and lengthy article text. You also included a web link, but the link is not yet active. You will add the code to make it active.
Also, the TextView by itself can't enable users to scroll the article text to see all of it. You will add a new view group called ScrollView
to the XML layout that will make the TextView scrollable.
2.1 Add the autoLink attribute for active web links
Add the android:autoLink="web"
attribute to the article
TextView. The XML code for this TextView should now look like this:
<TextView
android:id="@+id/article"
...
android:autoLink="web"
... />
2.2 Add a ScrollView to the layout
To make a view (such as a TextView) scrollable, embed the view inside a ScrollView.
Add a ScrollView between the article_subheading TextView and the article TextView. As you enter <ScrollView, Android Studio automatically adds
</ScrollView>
at the end, and presents theandroid:layout_width
andandroid:layout_height
attributes with suggestions. Choose wrap_content from the suggestions for both attributes. The code should now look like this:<TextView android:id="@+id/article_subheading" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/article_heading" android:padding="10dp" android:textAppearance="@android:style/TextAppearance" android:text="@string/article_subtitle"/> <ScrollView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/article_subheading"></ScrollView> <TextView android:id="@+id/article" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/article_subheading" android:lineSpacingExtra="5sp" android:autoLink="web" android:text="@string/article_text"/>
Move the ending
</ScrollView>
code after thearticle
TextView so that thearticle
TextView attributes are inside the ScrollView XML element.Remove the following attribute from the
article
TextView, because the ScrollView itself will be placed below thearticle_subheading
element, and this attribute for TextView would conflict with the ScrollView:android:layout_below="@id/article_subheading"
The layout should now look like this:
- Choose Code > Reformat Code to reformat the XML code so that the
article
TextView now appears indented inside the<Scrollview
code. Run the app.
Swipe up and down to scroll the article. The scroll bar appears in the right margin as you scroll.
Tap the web link to go to the web page. The
android:autoLink
attribute turns any recognizable URL in the TextView (such as www.rockument.com) into a web link.- Rotate your device or emulator while running the app. Notice how the scrolling view widens to use the full display and still scrolls properly.
- Run the app on a tablet or tablet emulator. Notice how the scrolling view widens to use the full display and still scrolls properly.
In the above figure, the following appear:
- An active web link embedded in free-form text
- The scroll bar that appears when scrolling the text
Depending on your version of Android Studio, the activity_main.xml layout file will now look something like the following:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.android.scrollingtext.MainActivity">
<TextView
android:id="@+id/article_heading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:textColor="@android:color/white"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textAppearance="@android:style/TextAppearance.Large"
android:textStyle="bold"
android:text="@string/article_title"/>
<TextView
android:id="@+id/article_subheading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/article_heading"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textAppearance="@android:style/TextAppearance"
android:text="@string/article_subtitle"/>
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/article_subheading">
<TextView
android:id="@+id/article"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5sp"
android:autoLink="web"
android:text="@string/article_text"/>
</ScrollView>
</RelativeLayout>
Solution code
Android Studio project: ScrollingText
Task 3: Scroll multiple elements
As noted before, the ScrollView view group can contain only one child view (such as the article
TextView you created); however, that View can be another view group that contains Views, such as LinearLayout. You can nest a view group such as LinearLayout within the ScrollView view group, thereby scrolling everything that is inside the LinearLayout.
For example, if you want the subheading of the article to scroll along with the article, add a LinearLayout within the ScrollView, and move the subheading, along with the article, into the LinearLayout. The LinearLayout view group becomes the single child View in the ScrollView as shown in the figure below, and the user can scroll the entire view group: the subheading and the article.
3.1 Add a LinearLayout to the ScrollView
- On your computer, make a copy of Android Studio's project folder for ScrollingText, and rename the project to be ScrollingText2. To copy and rename a project, follow the "Copy and rename a project" instructions in the Appendix.
- Open ScrollingText2 in Android Studio, and open the activity_main.xml file to change the XML layout code.
Add a LinearLayout above the
article
TextView in the ScrollView. As you enter <LinearLayout, Android Studio automatically adds</LinearLayout>
to the end, and presents theandroid:layout_width
andandroid:layout_height
attributes with suggestions. Choose match_parent and wrap_content from the suggestions for its width and height, respectively. The code should now look like this:<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"></LinearLayout>
You use
match_parent
to match the width of the parent view group, andwrap_content
to make the view group only big enough to enclose its contents and padding.- Move the ending
</LinearLayout>
code after thearticle
TextView but before the closing</ScrollView>
so that the LinearLayout includes thearticle
TextView and is completely inside the ScrollView. Add the
android:orientation="vertical"
attribute to the LinearLayout in order to set the orientation of the LinearLayout to vertical. The LinearLayout within the ScrollView should now look like this (choose Code > Reformat Code to indent the view groups correctly):<ScrollView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/article_subheading"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/article" android:layout_width="wrap_content" android:layout_height="wrap_content" android:autoLink="web" android:lineSpacingExtra="5sp" android:text="@string/article_text" /> </LinearLayout> </ScrollView>
- Move the
article_subheading
TextView to a position inside the LinearLayout above thearticle
TextView. - Remove the
android:layout_below="@id/article_heading"
attribute from thearticle_subheading
TextView. Since this TextView is now within the LinearLayout, this attribute would conflict with the LinearLayout attributes. - Change the ScrollView layout attribute from
android:layout_below="@id/article_subheading"
toandroid:layout_below="@id/article_heading"
. Now that the subheading is part of the LinearLayout, the ScrollView must be placed below the heading, not the subheading. - Run the app.
Swipe up and down to scroll the article, and notice that the subheading now scrolls along with the article while the heading stays in place.
Solution code
Android Studio project: ScrollingText2
Coding challenge
Challenge: Add another UI element—a Button—to the LinearLayout view group that is contained within the ScrollView. Make the Button appear below the article. The user would have to scroll to the end of the article to see the button. Use the text "Add Comment" for the Button, for users to click to add a comment to the article. For this challenge, there is no need to create a button-handling method to actually add a comment; it is sufficient to just place the Button element in the proper place in the layout.
Challenge Solution code
Android Studio project: ScrollingText3
Summary
In this practical, you learned about Android Studio's view elements and how to scroll and nest code.You worked to:
- Add multiple TextView elements to the XML layout.
- Display free-form text in a TextView with HTML formatting tags for bold and italics.
- Use \n as an end-of-line character in free-form text to keep a paragraph from running into the next paragraph.
- Use the
android:autoLink="web"
attribute to make web links in the text clickable.
- Add a ScrollView view group to the layout to define a scrolling view with one of the TextView elements.
- Add a LinearLayout view group within a ScrollView in order to scroll several TextView elements together.
- Extract string values into string names in the strings.xml file for easier localization of string resources.
Related concepts
The related concept documentation is in Android Developer Fundamentals: Concepts.
Learn more
Developer Documentation:
Other:
- Android Developers Blog: Linkify your Text!
- Codepath: Working with a TextView