Android 学习日报 Text and scrolling views

127 阅读9分钟

Android developer document - 1.3: Text and scrolling views

This chapter describes one of the most often used View subclasses in apps: the TextView, which shows textual content on the screen. A TextView can be used to show a message, a response from a database, or even entire magazine-style articles that users can scroll. This chapter also shows how you can create a scrolling view of text and other elements.

本章介绍应用程序中最常用的 View 子类之一:TextView,它在屏幕上显示文本内容。 TextView 可用于显示消息、数据库的响应,甚至用户可以滚动浏览整篇杂志风格的文章。 本章还介绍了如何创建文本和其他元素的滚动视图。

TextView

If you want to allow users to edit the text, use EditText, a subclass of TextView that allows text input and editing.

如果要允许用户编辑文本,请使用 EditText,它是 TextView 的子类,允许文本输入和编辑。

TextView attributes

您可以使用 TextView 的 XML 属性来控制:

  • TextView 在布局中的位置(与任何其他视图一样)
  • TextView 本身的显示方式,例如背景颜色
  • 文本在 TextView 中的外观,例如初始文本及其样式、大小和颜色

You can extract the text string into a string resource (perhaps called hello_world) that's easier to maintain for multiple-language versions of the app, or if you need to change the string in the future.

您可以将文本字符串提取到字符串资源(可能称为 hello_world)中,这样对于应用程序的多语言版本或将来需要更改字符串时更容易维护。

<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/hello_world"
   <!-- more attributes -->
/>

In addition to android:layout_width and android:layout_height (which are required for a TextView), the most often used attributes with TextView are the following:

之外,TextView 最常用的属性如下:

  • android:text: Set the text to display.
  • android:textColor: Set the color of the text. You can set the attribute to a color value, a predefined resource, or a theme. 设置文本的颜色。 您可以将该属性设置为颜色值、预定义资源或主题。
  • android:textAppearance: The appearance of the text, including its color, typeface, style, and size. You set this attribute to a predefined style resource or theme that already defines these values. 文本的外观,包括颜色、字体、样式和大小。 您可以将此属性设置为已定义这些值的预定义样式资源或主题。
  • android:textSize: Set the text size (if not already set by android:textAppearance). Use sp (scaled-pixel) sizes such as 20sp or 14.5sp, or set the attribute to a predefined resource or theme. 设置文本大小(如果尚未通过 android:textAppearance 设置)。 使用 sp(缩放像素)大小,例如 20sp 或 14.5sp,或将属性设置为预定义的资源或主题。
  • android:textStyle: Set the text style (if not already set by android:textAppearance). Use normal, bold, italic, or bold|italic. 设置文本样式(如果尚未通过 android:textAppearance 设置)。 使用正常、粗体、斜体或粗体|斜体。
  • android:typeface: Set the text typeface (if not already set by android:textAppearance). Use normal, sans, serif, or monospace. 设置文本字体(如果尚未通过 android:textAppearance 设置)。 使用普通、无衬线、衬线或等宽字体。
  • android:lineSpacingExtra: Set extra spacing between lines of text. Use sp (scaled-pixel) or dp (device-independent pixel) sizes, or set the attribute to a predefined resource or theme. 设置文本行之间的额外间距。 使用 sp(缩放像素)或 dp(与设备无关的像素)大小,或将属性设置为预定义的资源或主题。
  • android:autoLink: Controls whether links such as URLs and email addresses are automatically found and converted to clickable (touchable) links. 控制是否自动查找 URL 和电子邮件地址等链接并将其转换为可单击(可触摸)的链接。

Use one of the following with android:autoLink:

  • none: Match no patterns (default).
  • web: Match web URLs.
  • email: Match email addresses.
  • phone: Match phone numbers.
  • map: Match map addresses.
  • all: Match all patterns (equivalent to web|email|phone|map).

For example, to set the attribute to match web URLs, use android:autoLink="web".

Using embedded tags in text

To properly display in a text view, text must be formatted following these rules:

要在文本视图中正确显示,文本的格式必须遵循以下规则:

  • 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 </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.
  • To create a long string of text in the strings.xml file, enclose the entire text within <string name="your_string_name"></string> (your_string_name is the name you provide the string resource, such as article_text).
  • 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.

Referring to a TextView in code

To refer to a TextView in your Java code, use its resource id.

Find the TextView and assign it to a variable. You use the findViewById() method of the View class, and refer to the view you want to find using this format:

In which view_id is the resource identifier for the view (such as show_count) :

//  R.id.view_id
TextView mShowCount = (TextView) findViewById(R.id.show_count);

After retrieving the View as a TextView member variable, you can then set the text to new text (in this case, mCount_text) using the setText() method of the TextView class:

mShowCount.setText(mCount_text);

Scrolling views

If the information you want to show in your app is larger than the device's display, you can create a scrolling view 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 combine views (such as a TextView and a Button) within a scrolling view.

还可以使用滚动视图在滚动视图中组合视图(例如 TextView 和 Button)。

Creating a layout with a ScrollView

The ScrollView class provides the layout for a vertical scrolling view. (For horizontal scrolling, you would use HorizontalScrollView.) ScrollView is a subclass of FrameLayout, which means that you can place only one View as a child within it; that child contains the entire contents to scroll.

ScrollView 类提供垂直滚动视图的布局。 (对于水平滚动,您可以使用 HorizontalScrollView。)ScrollView 是 FrameLayout 的子类,这意味着您只能将一个 View 作为子级放置在其中; 该子项包含要滚动的全部内容。

Even though you can place only one child View inside a ScrollView, the child View can be a ViewGroup with a hierarchy of child View elements, such as a LinearLayout. A good choice for a View within a ScrollView is a LinearLayout that is arranged in a vertical orientation.

即使您只能在 ScrollView 中放置一个子 View,该子 View 也可以是具有子 View 元素层次结构的 ViewGroup,例如 LinearLayout。 对于 ScrollView 中的 View 来说,一个不错的选择是沿垂直方向排列的 LinearLayout。

ScrollView and performance 性能

All of the contents of a ScrollView (such as a ViewGroup with View elements) occupy memory and the view hierarchy even if portions are not displayed on screen. This makes ScrollView useful for smoothly scrolling pages of free-form text, because the text is already in memory. However, a ScrollView with a ViewGroup with View elements can use up a lot of memory, which can affect the performance of the rest of your app.

即使部分内容未在屏幕上显示,ScrollView 的所有内容(例如具有 View 元素的 ViewGroup)也会占用内存和视图层次结构。 这使得 ScrollView 对于平滑滚动自由格式文本的页面非常有用,因为文本已经在内存中。 但是,带有 ViewGroup 和 View 元素的 ScrollView 可能会占用大量内存,这可能会影响应用程序其余部分的性能。

Using nested instances of LinearLayout can also lead to an excessively deep view hierarchy, which can slow down performance. Nesting several instances of LinearLayout that use the android:layout_weight attribute can be especially expensive as each child View needs to be measured twice. Consider using flatter layouts such as RelativeLayout or GridLayout to improve performance.

使用 LinearLayout 的嵌套实例还可能导致视图层次结构过深,从而降低性能。 嵌套使用 android:layout_weight 属性的 LinearLayout 的多个实例可能会特别昂贵,因为每个子 View 都需要测量两次。 考虑使用更扁平的布局(例如RelativeLayout 或GridLayout)来提高性能

Complex layouts with ScrollView may suffer performance issues, especially with images. We recommend that you not use images within a ScrollView. To display long lists of items, or images, consider using a RecyclerView, which is covered in another lesson.

使用 ScrollView 的复杂布局可能会遇到性能问题,尤其是图像。 我们建议您不要在 ScrollView 中使用图像。 要显示长列表或图像,请考虑使用 RecyclerView

ScrollView with a TextView

To display a scrollable magazine article on the screen, you might use a RelativeLayout that includes a separate TextView for the article heading, another for the article subheading, and a third TextView for the scrolling article text (see the figure below), set within a ScrollView. The only part of the screen that would scroll would be the ScrollView with the article text.

要在屏幕上显示可滚动的杂志文章,您可以使用relativelayout,其中包含一个单独的textview用于文章标题,另一个用于文章副标题,第三个textview用于滚动文章文本(参见下图),设置在 滚动视图。 屏幕上唯一会滚动的部分是带有文章文本的 ScrollView。

image.png

ScrollView with a LinearLayout

A ScrollView can contain only one child View; however, that View can be a ViewGroup that contains several View elements, such as LinearLayout. You can nest a ViewGroup such as LinearLayout within the ScrollView, thereby scrolling everything that is inside the LinearLayout.

一个ScrollView只能包含一个子View; 但是,该 View 可以是包含多个 View 元素的 ViewGroup,例如 LinearLayout。 您可以在 ScrollView 中嵌套 ViewGroup(例如 LinearLayout),从而滚动 LinearLayout 内的所有内容。

For example, if you want the subheading of an article to scroll along with the article even if they are separate TextView elements, add a LinearLayout to the ScrollView as a single child View as shown in the figure below, and then move the TextView subheading and article elements into the LinearLayout. The user scrolls the entire LinearLayout which includes the subheading and the article.

例如,如果您希望文章的副标题与文章一起滚动,即使它们是单独的 TextView 元素,也可以将 LinearLayout 作为单个子 View 添加到 ScrollView 中,如下图所示,然后将 TextView 副标题移动到滚动视图中: 将文章元素放入 LinearLayout 中。 用户滚动整个 LinearLayout,其中包括副标题和文章。

image.png

When adding a LinearLayout inside a ScrollView, use match_parent for the LinearLayout android:layout_width attribute to match the width of the parent ScrollView, and use wrap_content for the LinearLayout android:layout_height attribute to make it only large enough to enclose its contents.

在 ScrollView 中添加 LinearLayout 时,使用 LinearLayout android:layout_width 属性的 match_parent 来匹配父 ScrollView 的宽度,并使用 LinearLayout android:layout_height 属性的 wrap_content 使其足够大以包围其内容。

Since ScrollView only supports vertical scrolling, you must set the LinearLayout orientation attribute to vertical (android:orientation="vertical"), so that the entire LinearLayout will scroll vertically. For example, the following XML layout scrolls the article TextView along with the article_subheading TextView:

由于ScrollView只支持垂直滚动,所以必须将LinearLayout的orientation属性设置为vertical(android:orientation="vertical"),这样整个LinearLayout才会垂直滚动。 例如,以下 XML 布局将文章 TextView 与article_subheading TextView 一起滚动:

<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>