Open In App
Related Articles

How to Underline Text in TextView in Android?

Improve Article
Save Article
Like Article

In Android, a TextView is a primary UI element used to display text present in the form of characters, numbers, strings, and paragraphs. However, styles cannot be applied to text present in the TextView. So in this article, we will show you how you could underline text in a TextView in Android. Follow the below steps once the IDE is ready.

TextView in Android

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add a TextView as shown below.


<?xml version="1.0" encoding="utf-8"?>
        app:layout_constraintTop_toTopOf="parent" />

Step 3: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.


package org.geeksforgeeks.underlinetext
import android.os.Bundle
import android.text.SpannableString
import android.widget.TextView
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // Declaring and initializing 
        // the TextView from layout
        val mTextView = findViewById<TextView>(
        // Declaring a string
        val mString = "Hello Geek!"
        // Creating a Spannable String 
        // from the above string
        val mSpannableString = SpannableString(mString)
        // Setting underline style from 
        // position 0 till length of
        // the spannable string
        mSpannableString.setSpan(UnderlineSpan(), 0, mSpannableString.length, 0)
        // Displaying this spannable
        // string in TextView
        mTextView.text = mSpannableString


You can see that the string is now underlined.


Last Updated : 06 Feb, 2022
Like Article
Save Article
Similar Reads