TextView Widget in Android with XML Attributes and Examples

TextView Widget in Android with XML Attributes and Examples

TextView Widget in Android with Examples and XML Attributes

TextView is one of the most basic and frequently used widgets in Android development. As the name suggests, it is used to display text on the screen – titles, labels, messages, descriptions, or any static text content in your UI.

Even though TextView looks simple, it is extremely powerful and customizable through a rich set of XML attributes. By mastering TextView, you can control text size, color, style, fonts, paddings, drawables, links, truncation, and more with just a few lines of XML.


What Is TextView in Android?

TextView is a subclass of the View class used to display text to the user. It does not accept input by default (for editable text you use EditText), but you can still make a TextView clickable or interactive if needed.

In almost every Android screen, you will find several TextViews used for headings, labels, hints, button-like text, error messages, or descriptive content. Because of that, understanding its properties is essential for creating polished Android UIs.


Basic Syntax of TextView in XML

A simple TextView defined in an XML layout file looks like this:

<TextView
    android:id="@+id/tvHello"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello TextView" />

This example sets an ID, width, height, and a text value. You can then reference this TextView in your activity or fragment and modify it programmatically.


Creating and Using TextView – Complete Example

Let’s build a small example that displays a greeting message using TextView and changes it when the user taps it. We’ll define the TextView in XML and then modify it from Kotlin (you can easily adapt it to Java).


Step 1: Layout XML (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="16dp">

    <TextView
        android:id="@+id/tvMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tap me to change text"
        android:textSize="20sp"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:padding="12dp" />

</LinearLayout>


Here we use a vertical LinearLayout with centered content and a single TextView inside it, with some basic styling applied.


Step 2: Kotlin Code (MainActivity.kt)

package com.example.textviewdemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val tvMessage = findViewById<TextView>(R.id.tvMessage)

        // Set initial text programmatically (optional)
        tvMessage.text = "Hello from TextView"

        tvMessage.setOnClickListener {
            tvMessage.text = "Text changed on click!"
            Toast.makeText(this, "TextView clicked", Toast.LENGTH_SHORT).show()
        }
    }
}

When you run this app, you’ll see the TextView in the center. Tapping on it changes the text and shows a Toast message, demonstrating both display and basic interaction.


Important XML Attributes of TextView in Android

TextView has many XML attributes. Below are some of the most commonly used and helpful ones, grouped by purpose, along with short descriptions and mini examples.

1. Basic Identity and Text Content

  • android:id – Assigns a unique ID so you can reference the TextView in code.
  • android:text – Sets the text to be displayed.
  • android:hint – Shows a hint when no text is present (more typical in EditText, but can be used in TextView too).
<TextView
    android:id="@+id/tvTitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Welcome"
    android:hint="Title here" />


2. Size and Position

  • android:layout_width / android:layout_height – Dimensions of the TextView (wrap_content, match_parent, or a specific dp value).
  • android:width / android:height – Explicit width/height in pixels (not recommended; use dp via layout_width/layout_height instead).
  • android:padding, android:paddingLeft, android:paddingRight etc. – Inner spacing around the text.
  • android:gravity – Controls how the text is placed inside the TextView’s own bounds (e.g., center, center_vertical, center_horizontal).
<TextView
    android:id="@+id/tvCentered"
    android:layout_width="200dp"
    android:layout_height="80dp"
    android:text="Centered text"
    android:gravity="center"
    android:padding="8dp" />


3. Text Appearance (Color, Size, Style, Font)

  • android:textColor – Sets the color of the text (e.g., @android:color/black or a custom color resource).
  • android:textSize – Sets the font size, usually in sp (scale-independent pixels).
  • android:textStyle – Makes the text bold, italic, or bold|italic.
  • android:textAllCaps – If true, displays all letters in uppercase.
  • android:typeface – Sets the font family (normal, sans, serif, monospace).
<TextView
    android:id="@+id/tvStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Styled TextView"
    android:textColor="@android:color/holo_blue_dark"
    android:textSize="18sp"
    android:textStyle="bold"
    android:textAllCaps="true"
    android:typeface="serif" />


4. Line Handling, Length, and Ellipsize

  • android:singleLine – Forces the TextView to display only one line (deprecated, use maxLines="1" instead).
  • android:maxLines / android:minLines – Sets the maximum or minimum number of lines.
  • android:lines – Fixes the TextView to a specific number of lines.
  • android:maxLength – Limits the number of characters.
  • android:ellipsize – Truncates long text with “…” (values like end, start, middle, marquee).

<TextView
    android:id="@+id/tvEllipsize"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:text="This is a very long text that may not fit in a single line."
    android:maxLines="1"
    android:textSize="18sp"
    android:ellipsize="end" />


In this example, if the text is longer than the available width, it will be cut and replaced with “…” at the end.


5. Drawables Around Text

TextView can display small images (drawables) to the left, right, top, or bottom of the text using these attributes:

  • android:drawableLeft / android:drawableStart
  • android:drawableRight / android:drawableEnd
  • android:drawableTop
  • android:drawableBottom
  • android:drawablePadding – Sets the spacing between the text and the drawable.
<TextView
    android:id="@+id/tvWithIcon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Profile"
    android:drawableLeft="@drawable/ic_person"
    android:drawablePadding="8dp"
    android:textSize="16sp" />

This creates a label with an icon on the left and some padding between the icon and the text. This pattern is useful for settings screens, menus, or list items.


6. Auto-Linking and Input Behavior

  • android:autoLink – Automatically converts URLs, phone numbers, email addresses, and map addresses into clickable links. Values: web, phone, email, map, all.
  • android:inputType – More common in EditText, but can be applied when using TextView as a read-only field with a specific input type.
  • android:cursorVisible – Controls whether the cursor is visible (relevant when TextView is focusable/editable).

<TextView
    android:id="@+id/tvLink"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Visit https://developer.android.com for documentation"
    android:autoLink="web"
    android:linksClickable="true" />

With autoLink="web", the URL in the text becomes a clickable link that opens in a browser.


7. Gravity vs Layout Gravity

It’s important to distinguish between:

  • android:gravity – Aligns the text inside the TextView itself.
  • android:layout_gravity – Controls how the TextView is positioned inside its parent layout.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal">

    <TextView
        android:id="@+id/tvGravityDemo"
        android:layout_width="200dp"
        android:layout_height="80dp"
        android:text="Inner centered"
        android:gravity="center"
        android:textSize="18sp"
        android:textStyle="bold"
        android:background="@android:color/darker_gray" />

</LinearLayout>


Here, the parent LinearLayout centers the TextView horizontally, and the TextView’s own gravity="center" centers the text within its gray box.


Creating TextView Programmatically

While XML is the most common way to define TextViews, you can also create them entirely from code. This is useful for dynamic forms, lists, or when the number of views is not known at design time.

val parentLayout = findViewById<LinearLayout>(R.id.rootLayout)

val dynamicTextView = TextView(this).apply {
    text = "I was created in Kotlin!"
    textSize = 18f
    setTextColor(getColor(android.R.color.holo_red_dark))
    setPadding(16, 16, 16, 16)
}

parentLayout.addView(dynamicTextView)

You can set any of the properties directly in code using setter methods such as setText(), setTextColor(), or property accessors like textSize, typeface, etc.


Best Practices When Using TextView

  • Use string resources (@string/...) instead of hardcoding text to support localization and reuse.
  • Always use sp units for android:textSize so the text scales correctly with user font settings.
  • Use colors from resources for consistency and easy theme management.
  • Limit lines and use ellipsize where necessary to avoid UI breaking due to long text.
  • Use styles and themes to define common TextView appearance and reduce duplication in XML.

Conclusion

TextView is a core widget in Android that you will use on almost every screen. With just a few XML attributes, you can control how your text looks, behaves, and interacts with users: from simple labels to clickable links and icon-text combinations.

By combining TextView’s XML attributes with Kotlin or Java code, you can build clean, readable, and accessible interfaces that feel professional and consistent across your entire Android application.

Post a Comment

0 Comments