Android TutorialsNo Comments

andro-indian1.png
463 views.

The Android TextView component is a View subclass which is capable of showing text. Being a subclass of View the TextView component can be used in your Android app’s GUI inside a ViewGroup, or as the content view of an activity.

Creating a TextView
You can create a TextView instance either by declaring it inside a layout XML file or by instantiating it programmatically. I will cover both ways of creating a TextView in the following sections.

Creating a TextView in a Layout File

Creating a TextView inside an Android layout XML file is done by inserting a TextView element into the layout file at the place where you want the TextView to be displayed. Here is an example layout file declaring a TextView:

Notice the TextView XML element inside the RelativeLayout element. This TextView element declares a TextView object. The other layout attributes are covered in my tutorial about Android layout.

Once the layout file is used as the content view of an Activity subclass you can obtain a reference to the TextView instance like this:

Creating a TextView Programmatically

You can also instantiate an Android TextView programmatically. Here is an Android TextView instantiation example:

This example creates a TextView instance, sets its text and adds it to the root layout of the activity.

Set The Text of The TextView
You can set the text to be displayed in the TextView either when declaring it in your layout file, or by using its setText() method.

Here is an XML example showing how to set the text of a declared TextView in a layout file:

The text is set via the android:text attribute. You can either set the text as attribute value directly, or reference a text defined in the strings.xml as is the case in the example above.

Here is a TextView setText() example, setting the text programmatically:

textView.setText(“Hey, one more TextView”);
Displaying HTML in a TextView
The Android TextView component can also display HTML. Here is how you do that:

The HTML the TextView is able to display is limited, though. If you need to display more advanced HTML, use the Android WebView.

Be the first to post a comment.

Add a comment