CodeLab:Android fundamentals 01.3:Text and scrolling views

Android fundamentals 01.3:Text and scrolling views


Tutorial source : Google CodeLab
Date : 2021/04/06

Complete course : 教程目录 (java).

Note : The link in this article requires Google access


1、Welcome

This practical codelab is part of Unit 1: Get started in the Android Developer Fundamentals (Version 2) course. You will get the most value out of this course if you work through the codelabs in sequence:

Note: This course uses the terms “codelab” and “practical” interchangeably.

Introduction

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 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. Place only one view as a child within it—a child view contains the entire contents to scroll. This child view may itself be a ViewGroup (such as LinearLayout) containing UI elements.

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 items that the user can scroll through (such as TextView elements).

With a ScrollView, all of the UI elements 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 lesson.

What you should already know

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.

What you’ll learn

  • How to use XML code to add multiple TextView elements.
  • How to use XML code to define a scrolling View.
  • How to display free-form text with some HTML formatting tags.
  • How to style the TextView background color and text color.
  • How to include a web link in the text.

What you’ll do

  • Create the ScrollingText app.
  • Change the ConstraintLayout ViewGroup to RelativeLayout.
  • 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.


2、App overview

The Scrolling Text app demonstrates the ScrollView UI component. ScrollView is a ViewGroup 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:

  1. An active web link embedded in free-form text
  2. The scroll bar that appears when scrolling the text


3、Task 1: Add and edit TextView elements

In this practical, you will create an Android project for the ScrollingText app, add TextView elements 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 this task you will create the project and the TextView elements, and use TextView attributes for styling the text and background.

Tip: To learn more about these attributes, see the TextView reference.

  1. In Android Studio create a new project with the following parameters:
AttributeValue
Application NameScrolling Text
Company Nameandroid.example.com (or your own domain)
Phone and Tablet Minimum SDKAPI15: Android 4.0.3 IceCreamSandwich
TemplateEmpty Activity
Generate Layout File checkboxSelected
Backwards Compatibility (AppCompat) checkboxSelected
  1. In the app > res > layout folder in the Project > Android pane, open the activity_main.xml file, and click the Text tab to see the XML code.

At the top, or root, of the View hierarchy is the ConstraintLayout ViewGroup:

android.support.constraint.ConstraintLayout
  1. Change this ViewGroup to RelativeLayout. The second line of code now looks something like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

RelativeLayout lets you place UI elements relative to each other, or relative to the parent RelativeLayout itself.

The default “Hello World” TextView element created by the Empty Layout template still has constraint attributes (such as app:layout_constraintBottom_toBottomOf="parent"). Don’t worry—you will remove them in a subsequent step.

  1. Delete the following line of XML code, which is related to ConstraintLayout:
xmlns:app="http://schemas.android.com/apk/res-auto"

The block of XML code at the top now looks like this:

<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"
    tools:context="com.example.android.scrollingtext.MainActivity">
  1. Add a TextView element above the “Hello World” TextView by entering <TextView. A TextView block appears that ends with /> and shows the layout_width and layout_height attributes, which are required for the TextView.
  2. Enter the following attributes for the TextView. As you enter each attribute and value, suggestions appear to complete the attribute name or value.
TextView #1 attributeValue
android:layout_width"match_parent"
android:layout_height"wrap_content"
android:id"@+id/article_heading"
android:background"@color/colorPrimary"
android:textColor"@android:color/white"
android:padding"10dp"
android:textAppearance"@android:style/TextAppearance.DeviceDefault.Large"
android:textStyle"bold"
android:text"Article Title"
  1. Extract the string resource for the android:text attribute’s hardcoded string "Article Title" in the TextView to create an entry for it in strings.xml.

Place the cursor on the hardcoded string, press Alt-Enter (Option-Enter on the Mac), and select Extract string resource. Make sure that the Create the resource in directories option is selected, and then edit the resource name for the string value to article_title.

String resources are described in detail in the String Resources. 8. Extract the dimension resource for the android:padding attribute’s hardcoded string "10dp" in the TextView to create dimens.xml and add an entry to it.

Place the cursor on the hardcoded string, press Alt-Enter (Option-Enter on the Mac), and select Extract dimension resource. Make sure that the Create the resource in directories option is selected, and then edit the Resource name to padding_regular. 9. Add another TextView element above the “Hello World” TextView and below the TextView you created in the previous steps. Add the following attributes to the TextView:

TextView #2 AttributeValue
layout_width"match_parent"
layout_height"wrap_content"
android:id"@+id/article_subheading"
android:layout_below"@id/article_heading"
android:padding"@dimen/padding_regular"
android:textAppearance"@android:style/TextAppearance.DeviceDefault"
android:text"Article Subtitle"

Because you extracted the dimension resource for the "10dp" string to padding_regular in the previously created TextView, you can use "@dimen/padding_regular" for the android:padding attribute in this TextView.

  1. Extract the string resource for the android:text attribute’s hardcoded string "Article Subtitle" in the TextView to article_subtitle.
  2. In the “Hello World” TextView element, delete the layout_constraint attributes:
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" 
  1. Add the following TextView attributes to the “Hello World” TextView element, and change the android:text attribute:
TextView AttributeValue
android:id"@+id/article"
android:layout_below"@id/article_subheading"
android:lineSpacingExtra"5sp"
android:padding"@dimen/padding_regular"
android:text"Article text"
  1. Extract the string resource for "Article text" to article_text, and extract the dimension resource for "5sp" to line_spacing.
  2. 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.

  1. In the app > res > values folder, open strings.xml.
  2. Open any text file with a large amount of text, or open the strings.xml file of the finished ScrollingText app.
  3. Enter the values for the strings article_title and article_subtitle with either a made-up title and subtitle, or use the values in the strings.xml file of the finished ScrollingText app. Make the string values single-line text without HTML tags or multiple lines.
  4. Enter or copy and paste text for the article_text string.

You can use the text in your text file, or use the text provided for the article_text string in the strings.xml file of the finished ScrollingText app. The only requirement for this task is that the text must be long enough so that it doesn’t fit 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. If you want the text in strings.xml to be wrapped, you can press Return to enter hard line endings, or format the text first in a text editor with hard line endings.
  • Enter \n to represent the end of a line, and another \n to represent a blank line. You need to add end-of-line characters to keep paragraphs from running into each other.
  • 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 tags around words that should be in bold.
  • Enter the HTML and tags around words that should be in italics. If you use curled apostrophes within an italic phrase, replace them with straight apostrophes.
  • You can combine bold and italics by combining the tags, as in words…. 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, because any HTML tags except the bold and italic tags are ignored and presented as text, which is not what you want.

在这里插入图片描述

1.3 Run the app

Run the app. The article appears, but the user can’t scroll the article 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.

在这里插入图片描述

Task 1 solution code

The activity_main.xml layout file looks 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"
   tools:context="com.example.android.scrollingtext.MainActivity">

   <TextView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:id="@+id/article_heading"
      android:background="@color/colorPrimary"
      android:padding="@dimen/padding_regular"
      android:text="@string/article_title"
      android:textAppearance=
                  "@android:style/TextAppearance.DeviceDefault.Large"
      android:textColor="@android:color/white"
      android:textStyle="bold" />

   <TextView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:id="@+id/article_subheading"
      android:layout_below="@id/article_heading"
      android:padding="@dimen/padding_regular"
      android:text="@string/article_subtitle"
      android:textAppearance=
                  "@android:style/TextAppearance.DeviceDefault" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/article"
      android:layout_below="@id/article_subheading"
      android:lineSpacingExtra="@dimen/line_spacing"
      android:padding="@dimen/padding_regular"
      android:text="@string/article_text" />

</RelativeLayout>


4、Task 2: Add a ScrollView and an active web link

In the previous task you created the ScrollingText app with TextView elements 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 ViewGroup 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 now looks like this:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/article"
        android:autoLink="web"
        android:layout_below="@id/article_subheading"
        android:lineSpacingExtra="@dimen/line_spacing"
        android:padding="@dimen/padding_regular"
        android:text="@string/article_text" />

2.2 Add a ScrollView to the layout

To make a View (such as a TextView) scrollable, embed the View inside a ScrollView.

  1. 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 the android:layout_width and android:layout_height attributes with suggestions.
  2. Choose wrap_content from the suggestions for both attributes.

The code for the two TextView elements and the ScrollView now looks like this:

<TextView
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:id="@+id/article_subheading"
   android:layout_below="@id/article_heading"
   android:padding="@dimen/padding_regular"
   android:text="@string/article_subtitle"
        android:textAppearance=
                     "@android:style/TextAppearance.DeviceDefault"/>

<ScrollView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"></ScrollView>

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/article"
        android:autoLink="web"
        android:layout_below="@id/article_subheading"
        android:lineSpacingExtra="@dimen/line_spacing"
        android:padding="@dimen/padding_regular"
        android:text="@string/article_text" />
  1. Move the ending </ScrollView> code after the article TextView so that the article TextView attributes are entirely inside the ScrollView.
  2. Remove the following attribute from the article TextView and add it to the ScrollView:
android:layout_below="@id/article_subheading"

With the above attribute, the ScrollView element will appear below the article subheading. The article is inside the ScrollView element.

  1. Choose Code > Reformat Code to reformat the XML code so that the article TextView now appears indented inside the <ScrollView code.
  2. Click the Preview tab on the right side of the layout editor to see a preview of the layout.

The layout now looks like the right side of the following figure:

在这里插入图片描述

2.3 Run the app

To examine how the text scrolls:

  1. Run the app on a device or emulator.

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.

  1. Rotate your device or emulator while running the app. Notice how the scrolling view widens to use the full display and still scrolls properly.
  2. 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:

  1. An active web link embedded in free-form text
  2. The scroll bar that appears when scrolling the text

Task 2 solution code

The XML code for the layout with the scroll view is as follows:

<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"
    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:padding="@dimen/padding_regular"
        android:text="@string/article_title"
        android:textAppearance=
                        "@android:style/TextAppearance.DeviceDefault.Large"
        android:textColor="@android:color/white"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/article_subheading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/article_heading"
        android:padding="@dimen/padding_regular"
        android:text="@string/article_subtitle"
        android:textAppearance=
                        "@android:style/TextAppearance.DeviceDefault" />

    <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:autoLink="web"
            android:lineSpacingExtra="@dimen/line_spacing"
            android:padding="@dimen/padding_regular"
            android:text="@string/article_text" />

    </ScrollView>

</RelativeLayout>


5、Task 3: Scroll multiple elements

As noted before, a ScrollView can contain only one child View (such as the article TextView you created). However, that View can be another ViewGroup that contains View elements, such as LinearLayout. You can nest a ViewGroup such as LinearLayout within the ScrollView, 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 and article into the LinearLayout. The LinearLayout becomes the single child View in the ScrollView as shown in the figure below, and the user can scroll the entire LinearLayout: the subheading and the article.

在这里插入图片描述

3.1 Add a LinearLayout to the ScrollView

  1. Open the activity_main.xml file of the ScrollingText app project, and select the Text tab to edit the XML code (if it is not already selected).
  2. Add a LinearLayout above the article TextView within the ScrollView. As you enter <LinearLayout, Android Studio automatically adds </LinearLayout> to the end, and presents the android:layout_width and android:layout_height attributes with suggestions. Choose match_parent and wrap_content from the suggestions for its width and height, respectively. The code at the beginning of the ScrollView now looks like this:
<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"></LinearLayout>

        <TextView
            android:id="@+id/article"

You use match_parent to match the width of the parent ViewGroup. You use wrap_content to resize the LinearLayout so it is just big enough to enclose its contents.

  1. Move the ending </LinearLayout> code after the article TextView but before the closing </ScrollView>.

The LinearLayout now includes the article TextView, and is completely inside the ScrollView.

  1. Add the android:orientation="vertical" attribute to the LinearLayout to set its orientation to vertical.
  2. Choose Code > Reformat Code to indent the code correctly.

The LinearLayout now looks like this:

<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="@dimen/line_spacing"
                android:padding="@dimen/padding_regular"
                android:text="@string/article_text" />
        </LinearLayout>

</ScrollView>

3.2 Move UI elements within the LinearLayout

The LinearLayout now has only one UI element—the article TextView. You want to include the article_subheading TextView in the LinearLayout so that both will scroll.

  1. To move the article_subheading TextView, select the code, choose Edit > Cut, click above the article TextView inside the LinearLayout, and choose Edit > Paste.
  2. Remove the android:layout_below="@id/article_heading" attribute from the article_subheading TextView. Because this TextView is now within the LinearLayout, this attribute would conflict with the LinearLayout attributes.
  3. Change the ScrollView layout attribute from android:layout_below="@id/article_subheading" to android: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.

The XML code for the ScrollView is now gas follows:

<ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/article_heading">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/article_subheading"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="@dimen/padding_regular"
                android:text="@string/article_subtitle"
                android:textAppearance=
                     "@android:style/TextAppearance.DeviceDefault" />

            <TextView
                android:id="@+id/article"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:autoLink="web"
                android:lineSpacingExtra="@dimen/line_spacing"
                android:padding="@dimen/padding_regular"
                android:text="@string/article_text" />
        </LinearLayout>

</ScrollView>
  1. 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.



6、Solution code

Android Studio project: ScrollingText



7、Coding challenge

Note: All coding challenges are optional and are not prerequisites for later lessons.

Challenge: Add another UI element—a Button—to the LinearLayout inside the ScrollView so that it scrolls with the text.

  • Make the Button appear below the article. The user scrolls to the end of the article to see the Button.
  • Use the text Add Comment for the Button. For this challenge, there is no need to create a button-handling method; all you have to do is put the Button element in the proper place in the layout.

在这里插入图片描述

Challenge solution code

Android Studio project: ScrollingTextChallenge



8、Summary

  • Use a ScrollView to scroll a single child View (such as a TextView). A ScrollView can hold only one child View or ViewGroup.
  • Use a ViewGroup such as LinearLayout as a child View within a ScrollView to scroll more than one View element. Enclose the elements within the LinearLayout.
  • 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.


9、Related concepts

The related concept documentation is in 1.3 Text and scrolling views.



10、Learn more

Android Studio documentation:

Android developer documentation:

Other:



11、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.

Change an app

Open the ScrollingText2 app that you created in the [Working with TextView Elements](https://google-developer-training.gitbooks.io/android-developer-fundamentals-course-practicals/content/Unit 1/13_p_working_with_textview_elements.html) lesson.

  1. Change the subheading so that it wraps within a column on the left that is 100 dp wide, as shown below.
  2. Place the text of the article to the right of the subheading as shown below.

在这里插入图片描述

Answer these questions

Question 1

How many views can you use within a ScrollView? Choose one:

  • One view only
  • One view or one view group
  • As many as you need

Question 2

Which XML attribute do you use in a LinearLayout to show views side by side? Choose one:

  • android:orientation="horizontal"
  • android:orientation="vertical"
  • android:layout_width="wrap_content"

Question 3

Which XML attribute do you use to define the width of the LinearLayout inside the scrolling view? Choose one:

  • android:layout_width="wrap_content"
  • android:layout_width="match_parent"
  • android:layout_width="200dp"

Submit your app for grading

Guidance for graders

Check that the app has the following features:

  • The layout shows the subheading in the left column and the article text in the right column, as shown in the above figure.
  • The ScrollView includes a LinearLayout with two TextView elements.
  • The LinearLayout orientation is set to horizontal.


12、Next codelab

To find the next practical codelab in the Android Developer Fundamentals (V2) course, see Codelabs for Android Developer Fundamentals (V2).

For an overview of the course, including links to the concept chapters, apps, and slides, see Android Developer Fundamentals (Version 2).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值