Tuesday, December 4, 2012

Android beginner tutorial: Part 10 - TextView introduction

Today we'll start learning about text widgets in Android.

A widget is any UI component in Android - a button, a text field, a slider, etc. You have a set of pre-built widgets to create your application with.

Today we will start learning about text widgets. There are two classes responsible for displaying text: TextView and EditText. The TextView class simply displays text on screen, without giving the user the ability to edit the text. If you want the text to be editable, use EditText.

Both of these classes inherit many properties and methods from the View class, and it should also be noted that EditText is a subclass of TextView.

In this tutorial we'll start learning about the first class I mentioned - TextView.

It's a simple but at the same time one of the most used widgets in Android applications. It is also used in other widgets for displaying text data, and quite a few widgets are actually extensions of this class. So, anything with text in it is related to TextView class one way or another.

You should keep that in mind, because TextView class has a few unique attributes and methods that are also available in any classes that extend TextView.

Properties for this class can be defined in XML layout file, or programmatically in a Java class.

For example, if you want to apply a text value to a TextView object, you can use that using the android:text XML attribute, or using the setText() method in Java. Usually the attribute and method names are similar (android:textColor and setTextColor();), but not always (android:textColorHighlight and setHighlightColor();).

I've already wrote about ids in Android, they can be defined using the android:id attribute and generally look like this:

android:id = "@+id/myObject"

And to refer to this object later, the plus symbol is emitted:


The text values can be defined using an id, which refer to separate objects in res/values/strings.xml file.

For example, if you set the text value of a TextView like this:

android:text = "@string/myText"

It would refer to this part in the strings.xml file and use that value:

<string name="myText">Hello world!</string>

To set the value similarly in Java:

TextView text = (TextView)findViewById(R.id.myObject);

The Java syntax might look strange to you if you've never dealt with it before. Here is what the same code would look like in AS3 syntax (note: not working code):

var text:TextView = (myObject as TextView);

The strings.xml should be used most of the time to declare text values, instead of hardcoding the values directly into the attribute. This is done mainly because of the ability to add new languages.

That's all for today. We'll continue next time.

Thanks for reading!

No comments:

Post a Comment