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:
- For the complete list of codelabs in the course, see Codelabs for Android Developer Fundamentals (V2).
- For details about the course, including links to all the concept chapters, apps, and slides, see Android Developer Fundamentals (Version 2).
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:
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.
| 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 | Selected |
| Backwards Compatibility (AppCompat) checkbox | Selected |
At the top, or root, of the View hierarchy is the ConstraintLayout ViewGroup:
android.support.constraint.ConstraintLayoutRelativeLayout 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.
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">| 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" |
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:
| 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.
| android:id | "@+id/article" |
| android:layout_below | "@id/article_subheading" |
| android:lineSpacingExtra | "5sp" |
| android:padding | "@dimen/padding_regular" |
| android:text | "Article text" |
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.
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"><TextViewandroid: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" /><TextViewandroid: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" /><TextViewandroid: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:
<TextViewandroid: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.
The code for the two TextView elements and the ScrollView now looks like this:
<TextViewandroid: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"/><ScrollViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"></ScrollView><TextViewandroid: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" />With the above attribute, the ScrollView element will appear below the article subheading. The article is inside the ScrollView element.
The layout now looks like the right side of the following figure:
2.3 Run the app
To examine how the text scrolls:
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.
In the above figure, the following appear:
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"><TextViewandroid: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" /><TextViewandroid: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" /><ScrollViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@id/article_subheading"><TextViewandroid: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
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.
The LinearLayout now includes the article TextView, and is completely inside the ScrollView.
The LinearLayout now looks like this:
<ScrollViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@id/article_subheading"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><TextViewandroid: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.
The XML code for the ScrollView is now gas follows:
<ScrollViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@id/article_heading"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><TextViewandroid: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" /><TextViewandroid: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>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 Studio download page
- Meet Android Studio
Android developer documentation:
- ScrollView
- LinearLayout
- RelativeLayout
- View
- Button
- TextView
- String resources
- Relative Layout
Other:
- Android Developers Blog: Linkify your Text!
- Codepath: Working with a TextView
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.
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).
總結
以上是生活随笔為你收集整理的CodeLab:Android fundamentals 01.3:Text and scrolling views的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一个阿里巴巴程序员的心路历程
- 下一篇: 解决Windows7右键菜单出现乱码的详