🔤TextView
TextView Attributes
You can use XML attributes for a TextView
to control:
Where the
TextView
is positioned in a layout (like any other view)How the
TextView
itself appears, such as with a background colorWhat the text looks like within the
TextView
, such as the initial text and its style, size, and color
For example, to set the width, height, and initial text value of the view:
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:
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:
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 byandroid:textAppearance
). Usesp
(scaled-pixel) sizes such as20sp
or14.5sp
, or set the attribute to a predefined resource or theme.android:textStyle
: Set the text style (if not already set byandroid:textAppearance
). Usenormal
,bold
,italic
, orbold
|italic
.android:typeface
: Set the text typeface (if not already set byandroid:textAppearance
). Usenormal
,sans
,serif
, ormonospace
.android:lineSpacingExtra
: Set extra spacing between lines of text. Usesp
(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 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"
.
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:
Find the
TextView
and assign it to a variable. You use thefindViewById()
method of theView
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
) :After retrieving the
View
as aTextView
member variable, you can then set the text to new text (in this case,mCount_text
) using thesetText()
method of theTextView
class:
Last updated