Android TextView is a UI component that is used to display text on the screen of an Android application. It is a versatile widget that can be customized to display different types of text, such as plain text, HTML formatted text, or even text with inline images. TextView can be used to display both static and dynamic text, and it supports various text formatting options, including font styles, sizes, colors, and alignment. Additionally, it can also handle user interaction by allowing the user to select, copy, and interact with the displayed text. Overall, TextView is an essential component for any Android app that requires text display functionality.
Dimensioning / Size
Height / Width – Explicit
The first and most direct way to control the width and height of an Android textview is to give explicit dimensions. To do so you must give both the target unit and the explicit number. The following list shows which units can be used for setting the width or height. You must be careful as some units might not scale well on every device. For instance, a pixel might be bigger / smaller on different screen sizes.
px
: Pixels – Corresponds to actual pixels on the screendp
: Density-independent Pixels – An abstract unit that is based on the physical density of the screen.- sp: Scale-independent Pixels – This is like the dp unit, but the user’s font size preference also scales it.
- pt: Points – 1/72 of an inch based on the physical size of the screen, assuming a 72dpi density screen.
- mm: Millimeters – Based on the physical size of the screen.
- in: Inches – Based on the physical size of the screen.
The best way to set exact dimensions is to do it directly in the XML layout file. The advantage is that it is directly calculated to the final pixel dimension. Defining the width and height programmatically is not as easy as setting the values directly in XML. The reason is that you must set the values in the layoutParams
object of the textview. This object’s width and height are displayed in pixels. So you must convert every value to the corresponding pixel value.
It might happen that your text content will be bigger than the size of the textview. You should check the scrolling behavior in this case.
XML – Explicit Width and Height
<TextView android:id="@+id/small" android:layout_height="10mm" android:layout_width="50mm" android:text="Small" ... /> <TextView android:id="@+id/big" android:layout_height="50mm" android:layout_width="50mm" android:text="Big" ... />
Kotlin – Explicit Width and Height
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val small = findViewById<TextView>(R.id.small) val big = findViewById<TextView>(R.id.big) val displayMetrics = resources.displayMetrics small.layoutParams.width = displayMetrics.mmToPixel(50) small.layoutParams.height = displayMetrics.mmToPixel(10) big.layoutParams.width = displayMetrics.mmToPixel(50) big.layoutParams.height = displayMetrics.mmToPixel(50) } } fun DisplayMetrics.mmToPixel(value : Int) : Int { return (this.xdpi * (1.0f/25.4f) * value).toInt() }
Height / Width – Match Parent
The second option is to match the dimension of the parent of the view. This option is great if your view needs to be responsive to auto-scaling. It will automatically adapt to any changes of the parent. When the parent container changes the textview will automatically adjust its size to fill the parent. You can create a view that is the full parent.
You can set the width and height of the textview by indicating match_parent
in the XML layout file or by indicating it programmatically in the constructor of the LayoutParam
Class. The MATCH_PARENT indicator is a constant integer (-1) that can be accessed by the static field in the ViewGroup.LayoutParams
class.
XML – Match Parent Width
<TextView android:id="@+id/match" android:layout_height="10mm" android:layout_width="match_parent" android:text="Match Parent Width" ... /> <TextView android:id="@+id/fixed" android:layout_height="50mm" android:layout_width="50mm" android:text="Fixed Size" ... />
Kotlin – Match Parent Width
val match = findViewById<TextView>(R.id.match) val fixed = findViewById<TextView>(R.id.fixed) match.layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
Height / Width – Wrap Content
In contrast to the match_parent
, which adjusts the size of the textview to the parent, wrap_content
will adjust the size of the textview to the containing text. This means that if you have a small text, the textview will be small. But it will automatically adjust to bigger texts as well. In this option, you don’t have to worry about scrolling behavior as your text is always visible.
You can set this option in the XML layout file with the wrap_content
option. Programmatically, you can access similarly this option in the layoutParams
member of the view, which you want to adapt.
XML – Width Wrap Content
<TextView android:id="@+id/longText" android:layout_height="10mm" android:layout_width="wrap_content" android:text="Long Text" ... /> <TextView android:id="@+id/shortText" android:layout_height="10mm" android:layout_width="wrap_content" android:text="S" ... />
Kotlin – Width Wrap Content
val short = findViewById<TextView>(R.id.shortText) val long = findViewById<TextView>(R.id.longText) short.layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT long.layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT
Height / Width – By Constraints
The last option we are going to propose is to control the size of the view by constraining its border to sibling views or parents. For example, if you constrain both the left and right border the width of the view will be correctly calculated. This option scales very well for different screen sizes. In combination with match_parent
and wrap_content
you will get a truly responsive layout.
Note that you must put the width (or height) to 0 dp to enable the system to calculate the size by constraints.
XML – Width by constraint
<TextView android:id="@+id/left" android:layout_width="wrap_content" android:layout_height="match_parent" android:background="#F44336" android:gravity="center" android:text="Left" app:layout_constraintStart_toStartOf="parent" /> <TextView android:id="@+id/right" android:layout_width="wrap_content" android:layout_height="match_parent" android:background="#F44336" android:gravity="center" android:text="Right" app:layout_constraintEnd_toEndOf="parent" /> <TextView android:id="@+id/constraint" android:layout_width="0dp" android:layout_height="match_parent" android:background="#4CAF50" android:gravity="center" android:text="Middle" app:layout_constraintEnd_toStartOf="@+id/right" app:layout_constraintStart_toEndOf="@+id/left" />
Kotlin – Width by constraint
val left = findViewById<TextView>(R.id.left) val constraint = findViewById<TextView>(R.id.constraint) val right = findViewById<TextView>(R.id.constraint) val params = constraint.layoutParams as ConstraintLayout.LayoutParams params.leftToRight = left.id params.rightToLeft = right.id constraint.requestLayout()
Positioning
Position by constraints
Layout Constraint | ConstraintLayout.LayoutParams | Description |
---|---|---|
layout_constraintLeft_toLeftOf | leftToLeft | Left border to left border |
layout_constraintLeft_toRightOf | leftToRight | Left border to right border |
layout_constraintRight_toLeftOf | rightToLeft | Right border to left border |
layout_constraintRight_toRightOf | rightToRight | Right border to right border |
layout_constraintTop_toTopOf | topToTop | Top border to top border |
layout_constraintTop_toBottomOf | topToBottom | Top border to bottom border |
layout_constraintBottom_toTopOf | bottomToTop | Bottom border to top border |
layout_constraintBottom_toBottomOf | bottomToBottom | Bottom border to bottom border |
layout_constraintStart_toEndOf | startToEnd | Start of flow to end of flow |
layout_constraintStart_toStartOf | startToStart | Start of flow to start flow |
layout_constraintEnd_toStartOf | endToStart | End of flow to start of flow |
layout_constraintEnd_toEndOf | endToEnd | End of flow to end of flow |
Text Content
The main property of a text view is naturally the text content. You can bind the content within XML by setting the “android:text” field. You can either write directly your text or you can reference it within a lookup value from a different resource file. This would be the preferred way if the text must not be dynamically available. In Kotlin code you can directly set the text property as shown below.
XML
<TextView ... android:id="@+id/view" android:text="Hello World!" />
Code
val view = findViewById<TextView>(R.id.view) view.text = "Changed Hello World"
Text Size
The textsize determines how small or big the text will be displayed on your android phone. Ideally, this value should be defined in a resource file. You can set the textSize directly in the XML or programmatically.
XML
<TextView android:id="@+id/viewSmall" android:text="Small" android:textSize="14sp" ... /> <TextView android:id="@+id/viewBig" android:text="Big" android:textSize="60sp" ... />
Code
val viewSmall= findViewById<TextView>(R.id.viewSmall) val viewBig= findViewById<TextView>(R.id.viewBig) viewSmall.textSize = 14F viewBig.textSize = 65F
Text Color
The Android framework provides several ways to set the text color, either statically in XML or programmatically in code.
SetTextColor from RGB / HEX colors
The first option is to use hardcoded RGB, RGBA or HEX colors. You can write them directly in your XML file. Or you can specify the text color programmatically in your Android app. When using the HEX, RGB colors in your Kotlin code, the build in Color class provides some nice feature to parse it.
XML
<TextView android:id="@+id/viewBlue" android:textColor="#2196F3" ... /> <TextView android:id="@+id/viewRed" android:textColor="#E91E63" ... />
Code: From HEX Color Code
val viewBlue = findViewById<TextView>(R.id.viewBlue) val viewRed = findViewById<TextView>(R.id.viewRed) viewBlue.setTextColor(Color.parseColor("#2196F3")); viewRed.setTextColor(Color.parseColor("#E91E63"));
Code: From RGB / RGBA colors
viewBlue.setTextColor(Color.rgb(0, 0, 255)); viewRed.setTextColor(Color.rgb(255, 0, 0));
SetTextColor from predefined values
The second option is to use predefined (named) colors. You can either use internally defined colors (such as Color.Blue
) or you can use your own colors, which you can specify in specific resource bundles.
Code: From internal predefined colors
The color class has some build in colors.
viewBlue.setTextColor(Color.BLUE); viewRed.setTextColor(Color.RED);
Code / XML: From predefined colors
The colors in this example are defined in a resource bundle and can be accessed by the ContextCompat
class.
viewBlue.setTextColor(ContextCompat.getColor(this, R.color.blue)); viewRed.setTextColor(ContextCompat.getColor(this, R.color.red));
<resources> ... <color name="red">#E91E63</color> <color name="blue">#2196F3</color> </resources>
Text Style
With the textstyle you can control if your text is bold, italic or underlined. In XML it is quite straightforward. Programmatically it is not so easy to find, as you need to use the typeface interface.
XML
<TextView android:id="@+id/viewBold" android:textStyle="bold" ... /> <TextView android:id="@+id/viewItalic" android:textStyle="italic" ... />
Code
val viewBold = findViewById<TextView>(R.id.viewBold) val viewItalic = findViewById<TextView>(R.id.viewItalic) viewBold.setTypeface(null, Typeface.BOLD); viewItalic.setTypeface(null, Typeface.ITALIC);
Text Alignment
Android provides several ways to align the text in you app. The text is aligned with respect to the textview width and height. This means you need to define width / height which is not “wrap_content”. The following option is the easiest way to do it. However, it is recommended to use the Gravity property as it gives you much more control about the text alignment.
XML
<TextView android:id="@+id/viewLeft" android:layout_width="0dp" android:textAlignment="textStart" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" /> <TextView android:id="@+id/viewRight" android:layout_width="0dp" android:textAlignment="textEnd" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" />
Code
val viewLeft= findViewById<TextView>(R.id.viewLeft) val viewRight= findViewById<TextView>(R.id.viewRight) viewLeft.textAlignment = TextView.TEXT_ALIGNMENT_TEXT_START; viewRight.textAlignment = TextView.TEXT_ALIGNMENT_TEXT_END;
Background Color
XML
The background color can be easily given by using the “android:background” field. It accepts HEX color codes. You can also assign colors from other resources files.
<TextView android:id="@+id/viewRed" android:background="#E91E63" ... /> <TextView android:id="@+id/viewBlue" android:background="#3F51B5" ... />
Code
Similar to the text color there are several ways to set programmatically the background color of a textview in Kotlin. You can either use color codes such as RGB/RGBA or HEX. Or you can use predefined colors. With predefined colors you can either use Androids predefined colors or you can create your own color resources.
val viewRed = findViewById<TextView>(R.id.viewRed) val viewBlue = findViewById<TextView>(R.id.viewBlue) // RGB Colors viewRed.setBackgroundColor(Color.rgb(255, 0, 0)) viewBlue.setBackgroundColor(Color.rgb(0, 0, 255)) // HEX Colors viewRed.setBackgroundColor(Color.parseColor("#E91E63")) viewBlue.setBackgroundColor(Color.parseColor("3F51B5")) // Predefined internal Colors viewRed.setBackgroundColor(Color.RED) viewBlue.setBackgroundColor(Color.BLUE) // Predefined XML Colors viewRed.setTextColor(ContextCompat.getColor(this, R.color.red)); viewBlue.setTextColor(ContextCompat.getColor(this, R.color.blue));
Text alignment with Gravity
The most flexible way in aligning text within your app is to constrain the view and to give it; if necessary some width. Afterward, you can assign one or more gravity parameters to your view, which will affect the text position. You can set the gravity property in the Android XML file, or you can set the gravity parameter programmatically in your Kotlin code. Tip: Your view needs to have the correct width and height so that the gravity parameter works well (you should not use wrap_content).
Gravity Properties
The following options are available to align your text. They can be superimposed (as shown in the example) unless they are not contradictive to each other. For example, you can use Left and Right at the same time.
Bottom | Top | clip_horizontal |
Left | Right | clip_vertical |
center | center_horizontal | center_vertical |
fill | fill_horizontal | fill_vertical |
start | end |
XML
<TextView android:id="@+id/viewTopLeft" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="top|left" android:text="TopLeft" android:textSize="48sp" app:layout_constraintBottom_toTopOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/viewBottomRight" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="bottom|right" android:text="BottomRight" android:textSize="48sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="parent" />
Code
val topLeft = findViewById<TextView>(R.id.viewTopLeft) val bottomRight = findViewById<TextView>(R.id.viewBottomRight) topLeft.gravity = Gravity.TOP + Gravity.LEFT bottomRight.gravity = Gravity.BOTTOM + Gravity.RIGHT
Within the XML you can specify several gravity properties by using the “|” symbol. In code, you can add (binary mask) the static field values of the public gravity class (LINK).
Text Visibility
XML
The visibility of elements can be specified in the XML resource file with the “visibility” tag and the corresponding values.
<TextView android:id="@+id/isVisible" android:text="isVisible" android:visibility="visible" /> <TextView android:id="@+id/notVisible" android:text="notVisible" android:visibility="invisible" />
Code
In your Android application, you can programmatically set the visibility of the Kotlin text view by specifying the Enum values, coming from “View”.
val isVisible = findViewById<TextView>(R.id.isVisible) val notVisible = findViewById<TextView>(R.id.notVisible) isVisible.visibility = View.VISIBLE; notVisible.visibility = View.INVISIBLE;
Text Visibility with Alpha Channel
Another option to control text visibility is to specify the alpha channel. With this option, you even have more control over the visual appearance than the previous option.
The alpha channel is a floating point number with a range of 0.0 – 1.0. If you indicate 0.0 the view will be completely invisible. If you indicate 1.0 the view will be 100 % visible. All numbers in between will make the view somewhat transparent. In our example, we have put the “Invisible” text view to 50 % transparency.
Once again you specify the alpha channel in the XML resource file of your Android app. This option is recommended for static views. The other way is to set the alpha value dynamically from your Kotlin project files.
XML
<TextView android:id="@+id/isVisible" android:text="isVisible" android:alpha="1.0" /> <TextView android:id="@+id/notVisible" android:alpha="0.5" android:text="notVisible" />
Code
val isVisible = findViewById<TextView>(R.id.isVisible) val notVisible = findViewById<TextView>(R.id.notVisible) isVisible.alpha = 1.0f; notVisible.alpha = 0.5f;
Clickable Textview
By default a textview is clickable. You can register any OnClickListeners or OnTouchListeners to handle click and touch events.
XML
<TextView android:id="@+id/isClickable" android:text="isClickable" android:clickable="true" /> <TextView android:id="@+id/isNotClickable" android:text="isNotClickable" android:clickable="false" />
Code
private var nClicks = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val clickable = findViewById<TextView>(R.id.isVisible) val notClickable = findViewById<TextView>(R.id.notVisible) clickable.isClickable = true clickable.setOnClickListener { nClicks++; notClickable.text = "Clicked: $nClicks" } }
Additional Information and References
Official reference guide from Google
Other useful material