1.3: Text and Scrolling Views

Contents:

This chapter describes one of the most often used views 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.

TextView

One view you may use often is the TextView class, which is a subclass of the View class that displays text on the screen. You can use TextView for a view of any size, from a single character or word to a full screen of text. You can add a resource id to the TextView, and control how the text appears using attributes in the XML layout file.

You can refer to a TextView view in your Java code by using its resource id, and update the text from your code. If you want to allow users to edit the text, use EditText, a subclass of TextView that allows text input and editing. You learn all about EditText in another chapter.

TextView attributes

You can use XML attributes to control:

  • Where the TextView is positioned in a layout (like any other view)
  • How the view itself appears, such as with a background color
  • What the text looks like within the view, such as the initial text and its style, size, and color

For example, to set the width, height, and position within a LinearLayout:

<TextView
   ...
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   … />

To set the initial text value of the view, use the android:text attribute:

android:text="Hello World!"

A TextView Showing "Hello World!"

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. After extracting the string, use the string resource name with @string/ to specify the text:

android:text="@string/hello_world"

The most often used attributes with TextView are the following:

  • 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. Color resources and themes are described in other chapters.
  • 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:textStyle: Set the text style (if not already set by android:textAppearance). Use normal, bold, italic, or bold|italic.
  • Android:typeface: Set the text typeface (if not already set by android:textAppearance). Use normal, sans, serif, or monospace.
  • 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.
  • android:autoLink: Controls whether links such as URLs and email addresses are automatically found and converted to clickable (touchable) links. Use one of the following:

    • 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 this:

    android:autoLink="web"
    

Using embedded tags in text

In an app that accesses magazine or newspaper articles, the articles that appear would probably come from an online source or might be saved in advance in a database on the device. You can also create text as a single long string in the strings.xml resource.

In either case, the text may contain embedded HTML tags or other text formatting codes. To properly display in a text view, text must be formatted following these rules:

  • 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.
  • The TextView ignores all HTML tags except the following:
    • Use the HTML and </b> tags around words that should be in bold.
    • Use 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>.

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

Text lines in the strings.xml file 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. If you don't add end-of-line characters, the paragraphs will run into each other when displayed on the screen.

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. The endings will not be displayed on the screen.

Referring to a TextView in code

To refer to a TextView in your Java code, use its resource id. For example, to update a TextView with new text, you would:

  1. Find the TextView (with the id show_count) 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:

    R.id.view_id
    

    In which view_id is the resource identifier for the view:

    mShowCount = (TextView) findViewById(R.id.show_count);
    
  2. After retrieving the view as a TextView member variable, you can then set the text of the text view to the new 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.

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. A ScrollView with One Child View

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

ScrollView and performance

With a ScrollView, all of your views are in memory and in the view hierarchy even if they aren't displayed on screen. This makes ScrollView useful for smoothly scrolling pages of free-form text, 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.

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.

Complex layouts with ScrollView may suffer performance issues, especially with child views such as images. We recommend that you not use images with a ScrollView. To display long lists of items, or images, consider using a RecyclerView. Also, using AsyncTask provides a simple way to perform work outside the main thread, such as loading images in a background thread, then applying them to the UI once finished. AsyncTask is covered in another chapter.

ScrollView with a TextView

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

ScrollView with a LinearLayout

The ScrollView view group can contain only one view; however, that view can be a 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 an article to scroll along with the article even if they are separate TextViews, you can add a LinearLayout within the ScrollView, and move the subheading TextView, along with the article TextView, 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. A LinearLayout Inside the ScrollView

When adding a LinearLayout inside a ScrollView, use match_parent for the LinearLayout's android:layout_width attribute to match the width of the parent view group (the ScrollView), and use wrap_content for the LinearLayout's android:layout_height attribute to make the view group only big enough to enclose its contents and padding.

Since ScrollView only supports vertical scrolling, you must set the LinearLayout orientation to vertical (by using the android:orientation="vertical" attribute), 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
   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" />

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

   </LinearLayout>
</ScrollView>

The related exercises and practical documentation is in Android Developer Fundamentals: Practicals.

Learn more

results matching ""

    No results matching ""