Android TextView Using Kotlin With Example

In this article, we will learn about android Textview using Kotlin. We will go through various example that demonstrates how to use different attributes of textView. For example, how to make text of textView clickable, change textStyle to bold, italic. etc.

In this article, we will get answer to questions like –

  • What is TextView?
  • Why should we consider TextView while designing ui for any app?
  • What are possibilities using TextView while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Android TextView Using Kotlin Output Android TextView Using Kotlin programming language

Android TextView Using Kotlin Output

Video Output

Getting Started

We can define android Textview widget as below –

Android TextView widget is a View that are used to show texts to the user and optionally allow them to edit it. However, Text editing is disabled by default. You need to customise the basic class of TextView Widget to make it editable.

Now, how do we use TextView in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as TextView. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android TextView Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access TextView in Kotlin file without using findViewById() method.

Using TextView in Kotlin

Follow steps below to use TextView in newly created project –

  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <TextView
            android:id="@+id/textViewID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    Notice that we already have a TextView widget in xml file. Whenever we create any android application, a TextView widget is automatically added like this in xml file.

    Here, basic TextView is –

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />
    

    android:layout_width sets width of textView.
    android:layout_height sets height of textView.
    android:text sets text in textView.

  • We can also access it in Kotlin File, MainActivity.kt, as below –

    binding.textViewID.text = "Hello"
    

    Here, we have accessed textView as binding.textViewID.

Now, run this application. You will get output like below –

Tutorialwing Kotlin Android TextView Using Kotlin With Example

Sample App Output

There are many other things we can do with android textView using kotlin. Here, we will mostly use xml attributes to perform task in textView. However, We can also learn to use textView programmatically.

Different Attributes of TextView in XML

Let’s check how to use different attributes in textView to customise it –

Set Id of TextView

Many a time, we need id of View to access it in Kotlin file or create ui relative to that view in xml file. So, we can set id of textView using android:id attribute like below –

    <TextView
        android:id="@+id/textView"
        />

Here, we have set id of TextView as textView using android:id=”” attribute. So, if we need to reference this TextView, we need to use this id – textView.
Learn to Set ID of TextView Dynamically

Set Width of TextView

We use android:layout_width=”” attribute to set width of textView.
We can do it as below –

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of TextView Dynamically

Set Height of TextView

We use android:layout_height=”” attribute to set height of textView.
We can do it as below –

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of TextView Dynamically

Set Padding of TextView

We use android:padding=”” attribute to set padding of textView.
We can do it as below –

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in textView using android:padding=”” attribute.
Learn to Set Padding of TextView Dynamically

Set Margin of TextView

We use android:layout_margin=”” attribute to set margin of textView.
We can do it as below –

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in textView using android:layout_margin=”” attribute.
Learn to Set Margin of TextView Dynamically

Set Background of TextView

We use android:background=”” attribute to set background of textView.
We can do it as below –

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in textView using android:background=”” attribute.
Learn to Set Background of TextView Dynamically

Set Visibility of TextView

We use android:visibility=”” attribute to set visibility of textView.
We can do it as below –

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of textView using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of TextView Dynamically

Set Text of TextView

We use android:text=”” attribute to set text of textView.
We can do it as below –

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

Here, we have set text (“Hello Tutorialwing”) in textView using android:text=”” attribute.
Similarly, we can set any text using this attribute.
Learn to Set Text of TextView Dynamically

Set Color of Text in TextView

We use android:textColor=”” attribute to set color of text in textView.
We can do it as below –

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:textColor="#ffffff"     
        />

Here, we have set color (#ffffff i.e. white) of text (“Hello Tutorialwing”) in textView using android:textColor=”” attribute. Similarly, we can set any color using this attribute.
Learn to Set Color of TextView Dynamically

Set Gravity of TextView

We use android:gravity=”” attribute to set gravity of text in textView.
We can do it as below –

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:gravity="center_horizontal"
        />

Here, we have set gravity of text in textView using android:gravity=”” attribute. Attribute value can be – “center_horizontal”, “center”, “center_vertical” etc.
Learn to Set Gravity of TextView Dynamically

Set Text in Uppercase, Lowercase

If we need to show text of TextView in uppercase or lowercase etc.

Set text in uppercase

We can use android:textAllCaps=”true” attribute to set text in uppercase. We can do it as below –

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:textAllCaps="true"
        />

Attribute android:textAllCaps=”true” sets text in uppercase. So, HELLO TUTORIALWING is set in textView.

By default, false is set in this attribute. So, Whatever value is written in android:text=”” attribute, it will be set as it is. For example,

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:textAllCaps="false"
        />

Above code will set Hello Tutorialwing to textView.

How do we set text in lowercase?

Answer –

  • In xml file – write all the text in lowercase.
  • In kotlin file – take text as string. Then, convert it in lowercase. Then, set it to textView.

Learn to Set Text in Uppercase or Lowercase Dynamically

Set Size of Text in TextView

We use android:textSize=”” attribute to set size of text in textView.
We can do it as below –

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:textSize="20sp"
        />

Here, we have set size of text in textView using android:textSize=”” attribute.
Learn to Set Size of Text in TextView Dynamically

Set Style (Bold/italic) of Text in TextView

We use android:textStyle=”” attribute to set style (bold, italic etc.) of text in textView.
We can do it as below –

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:textStyle="bold"
        />

Here, we have set style of text in textView using android:textStyle=”” attribute. This attribute can take bold, italic or normal.

Set Letter Spacing of Text in TextView

We use android:letterSpacing=”” attribute to set spacing between letters of text in textView.
We can do it as below –

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:letterSpacing="1"
        />

Here, we have set spacing between letters of text in textView using android:letterSpacing=”” attribute.
Learn to Set Letterspacing of TextView Dynamically

Set Typeface of Text in TextView

We use android:typeface=”” attribute to set typeface in textView.
We can do it as below –

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:typeface="sans"
        />

Here, we have set typeface of text in textView using android:typeface=”” attribute. This attribute can take values – “sans”, “normal”, “monospace” or “normal”.
Learn to Set Typeface of TextView Dynamically

Set fontFamily of Text in TextView

We use android:fontFamily=”” attribute to set fontFamily of text in textView.
We can do it as below –

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Tutorialwing"
        android:fontFamily="sans-serif"
        />

Here, we have set fontFamily (Here, sans-serif) of text in textView using android:fontFamily=”sans-serif” attribute.

Till now, we have see how to use android textView using Kotlin. We have also gone through different attributes of TextView to perform certain task. Let’s have a look at list of such attributes and it’s related task.

Different Attributes of Android TextView Widget

Below are the various attributes that are used to customise android TextView Widget. However, you can check the complete list of attributes of Textview in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –

Sr. XML Attributes Description
1 android:autoLink This attribute is used to automatically detect url or emails and show it as clickable link.
2 android:autoText Use this attribute if you want to automatically correct spelling errors in text of the Textview.
3 android:capitalize If it is set, it means Textview has a textual input method and should automatically capitalize whatever the user types in the Textview.
4 android:id This attribute is use to provide unique ID to the Textview widget.
5 android:cursorVisible Use this attribute to make cursor visible or invisible. Default is visible.
6 android:drawableBottom Sets drawable(images etc.) below the text of the Textview.
7 android:drawableEnd Sets drawable(images etc.) to end of text in the Textview.
8 android:drawableLeft Sets drawable(images etc.) to left of text in the Textview.
9 android:drawablePadding Sets padding to the drawable(images etc.) in the Textview.
10 android:drawableRight Sets drawable(images etc.) to right of text in the Textview.
11 android:drawableStart Sets drawable(images etc.) to start of text in the Textview.
12 android:drawableTop Sets drawable(images etc.) to top of text in the Textview.
13 android:ellipsize Use this attribute when you want text to be ellipsized if it is longer than the Textview width.
14 android:ems Sets width of the Textview in ems.
15 android:gravity Use to align text of the Textview vertically or horizontally or both.
16 android:height Use to set height of the Textview.
17 android:hint Use to show hint when there is no text.
18 android:inputType Use to set input type of the Textview. It can be Number, Password, Phone etc.
19 android:lines Use to set height of the Textview by number of lines.
20 android:maxHeight Sets maximum height of the Textview.
21 android:minHeight Sets minimum height of the Textview.
22 android:maxLength Sets maximum character length of the Textview.
23 android:maxLines Sets maximum lines Textview can have.
24 android:minLines Sets minimum lines Textview can have.
25 android:maxWidth Sets maximum width Textview can have.
26 android:minWidth Sets minimum lines Textview can have.
27 android:text Sets text of the Textview
28 android:textAllCaps Use this attribute if you want to show all texts of the Textview in capital letters.
29 android:textColor Sets color of the text.
30 android:textSize Sets font size of the text.
31 android:textStyle Sets style of the text. For example, bold, italic, bolditalic.
32 android:typeface Sets typeface of the text. For example, normal, sans, serif, monospace.
33 android:width Sets width of the TextView.

We have seen different attributes of textView and how to use it. If you wish to visit post to learn more about it

Advance Concepts in Android TextView Using Kotlin

Till Now, we have seen how to use textView in android project. how to use different attributes to customize it. Now, we will go through some advance concepts in Android TextView Using Kotlin. For example, ellipsize text, clickable text, custom font in textView Widget.

Using Custom Font in TextView

Till now, we have seen how to use predefined fonts in textView. Now, we will see how to use custom fonts in textView. Follow steps below to set custom font –

  • At first, get the custom font you want to use in textView. We want to set Chantelli_Antiqua font in textView. So, download it from link provided.
  • Now, create assets folder inside src/main folder. Then, create fonts folder inside src/main/assets folder. Then, move Chantelli_Antiqua.ttf file inside …/fonts folder.
  • Now, write below code in MainActivity.kt file.
    // Create the TypeFace from the TTF asset
    val font = Typeface.createFromAsset(assets, "fonts/Chantelli_Antiqua.ttf")
    
    // Assign the typeface to the view
    binding.textView.typeface = font
    

    Above line gets font from ttf file and set in textView.

  • Finally, MainActivity.kt file contains below code –

    package com.tutorialwing.textview
    
    import android.graphics.Typeface
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    import com.tutorialwing.textview.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    
    		setCustomFont()
    	}
    
    	private fun setCustomFont() {
    
    		// Create the TypeFace from the TTF asset
    		val font = Typeface.createFromAsset(assets, "fonts/Chantelli_Antiqua.ttf")
    
    		// Assign the typeface to the view
    		binding.textView.typeface = font
    	}
    }
    
  • In activity_main.xml file, we have below code –

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello Tutorialwing!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • When you run app, output will be like –
    Tutorialwing Android Set Custom Font in TextView Kotlin Programmatically

    TextView using Chantelli_Antiqua font

Set Ellipsis Text in TextView

Have you ever needed ellipsis text in textView? Or, you don’t want to show all texts in long sentence in textView ? In textView, you can set such long sentence as ellipsis text.
Follow steps below to set ellipsis text in textView –

  • Add below line in textView to ellipsize text in it –
    android:ellipsize="end"
    android:singleLine="true"
    
  • So, open activity_main.xml file and add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true"
            android:padding="30dp"
            android:text="Hello Tutorialwing!, Adding long line to check ellipsis text in end inside textView"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • Run the app. We will get output like below –
    Tutorialwing Android Kotlin TextView Set Ellipsis Text Dynamically Programmatically
    We can set different value for android:ellipsize=”” attribute – start, middle, end etc. We have shown above output accordingly.

Create Shadow of Text in TextView

Sometimes we want to show shadow in text inside textView. We can follow below steps to do it –

  • Add below line in TextView to show shadow in text –
    android:shadowColor="#FFBB86FC"
    android:shadowDx="6"
    android:shadowDy="6"
    android:shadowRadius="2"
    
  • Open activity_main.xml file and add below code in it –

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="30dp"
            android:shadowColor="#FFBB86FC"
            android:shadowDx="6"
            android:shadowDy="6"
            android:shadowRadius="2"
            android:text="Hello Tutorialwing! Shadow in Text"
            android:textColor="@color/black"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • Now, run app. We will get output like below –
    Tutorialwing Android TextView Using Kotlin Shadow in Text in TextView Programmatically

Set Click Listener in TextView

Follow step below to set click listener in textView –

  • Open activity_main.xml file. Then, write below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:onClick="onClick"
            android:text="Hello Tutorialwing! Click on Me"
            android:textColor="@color/black"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    Here, we have used android:onClick=”” attribute to set click listener. Now, we will define onClick method in MainActivity.kt file to perform action when textView is clicked.

  • Open MainActivity.kt file. Then, add below code in it –

    package com.tutorialwing.textview
    
    import android.os.Bundle
    import android.view.View
    import android.widget.Toast
    import androidx.appcompat.app.AppCompatActivity
    import com.tutorialwing.textview.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity(), View.OnClickListener {
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    	}
    
    	override fun onClick(view: View?) {
    		when (view?.id) {
    			R.id.textView -> {
    				Toast.makeText(applicationContext, "Clicked on Hello Message", Toast.LENGTH_SHORT).show()
    			}
    		}
    	}
    }
    

    Now, run the app. A toast message is shown when textView is clicked.

Set Ripple Effect in TextView

We have already set click listener in textView. Now, follow step below to set ripple effect in textView –

  • Set background as below in textView –
    android:background="?android:attr/selectableItemBackground"
    
  • Then, run the app. Whenever textView is clicked, it shows ripple effect.

Detecting And Making URL clickable in Text in TextView

Sometimes we want textView to auto detect url present in textView. Also, we want url to be clickable. Follow steps below to do that –

  • We can use two attributes – android:autoLink=”” and android:linksClickable=”” in textView. Open activity_main.xml file. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:autoLink="all"
            android:gravity="center_horizontal"
            android:linksClickable="true"
            android:text="Hello URL: https://www.tutorialwing.com"
            android:textColor="@color/black"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    Run the app. You will notice that text https://www.tutorialwing.com is underlined and clickable.

Show html in TextView

How can we show html in textView?
Sometimes we want to style text using html format. Then, set styled text in textView. In Kotlin, we can do it as below –

  • We can set html in textView using Html.fromHtml() method –
    val formattedText = "This <i>is</i> a <b>test</b> of <a href='https://tutorialwing.com'>html text</a>"
    binding.textView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    	Html.fromHtml(formattedText, Html.FROM_HTML_MODE_LEGACY)
    } else {
    	Html.fromHtml(formattedText)
    }
    

Set Color in html Text in TextView

We can write as below to set text color in html for textView –

val formattedText = "Nice! <font color='#c5c5c5'>This text has a color</font>. This doesn't"

Here, we have used < font color='#c5c5c5' >Text to color to set color.

Show Image in TextView

We can show image in textView using drawableEndCompat=”” or drawableStartCompat=”” attributes.

  • Open activity_main.xml file. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:drawablePadding="8dp"
            android:gravity="center"
            android:text="Hello url https://www.tutorialwing.com"
            app:drawableEndCompat="@mipmap/ic_launcher"
            app:drawableStartCompat="@mipmap/ic_launcher"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    Now, run app. We will get output like below –
    Tutorialwing Android Kotlin TextView image in TextView programmatically

Using span to Style text in TextView

We can use span to style text as below –

  •     private fun customSpanFont() {
            val firstWord = "Hello"
            val secondWord = "Tutorialwing!"
    
            // Create a span that will make the text purple
            val redForegroundColorSpan = ForegroundColorSpan(
                resources.getColor(R.color.purple_200)
            )
    
            // Use a SpannableStringBuilder so that both the text and the spans are mutable
            val ssb = SpannableStringBuilder(firstWord)
    
            // Apply the color span
            ssb.setSpan(
                redForegroundColorSpan,  // the span to add
                0,  // the start of the span (inclusive)
                ssb.length,  // the end of the span (exclusive)
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            ) // behavior when text is later inserted into the SpannableStringBuilder
    
            // Add a blank space
            ssb.append(" ")
    
            // Create a span that will strike through the text
            val strikeThroughSpan = StrikethroughSpan()
    
            // Add the secondWord and apply the strikethrough span to only the second word
            ssb.append(secondWord)
            ssb.setSpan(
                    strikeThroughSpan,
                ssb.length - secondWord.length,
                ssb.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
    
            // Set the TextView text and denote that it is Editable
            // since it's a SpannableStringBuilder
            binding.textView.setText(ssb, TextView.BufferType.EDITABLE)
        }
    

Creating Clickable text using span in textView

Sometimes we want to set text using span. While doing so, we also want to set partial text as clickable. We can do it as below –

  • Create a file PatternEditableBuilder.kt in com.tutorialwing.textview package. Then, add below code in it –
    package com.tutorialwing.textview
    
    import android.text.SpannableStringBuilder
    import android.text.Spanned
    import android.text.TextPaint
    import android.text.method.LinkMovementMethod
    import android.text.style.ClickableSpan
    import android.view.View
    import android.widget.TextView
    import java.util.*
    import java.util.regex.Pattern
    
    class PatternEditableBuilder {
    
    	// Records the pattern spans to apply to a TextView
    	var patterns: ArrayList<SpannablePatternItem> = ArrayList()
    
    	/* This stores a particular pattern item complete with pattern, span styles, and click listener */
    	inner class SpannablePatternItem(var pattern: Pattern, var styles: SpannableStyleListener?, var listener: SpannableClickedListener?)
    
    	/* This stores the style listener for a pattern item, used to style a particular category of spans */
    	abstract class SpannableStyleListener {
    		var spanTextColor = 0
    
    		constructor() {}
    		constructor(spanTextColor: Int) {
    			this.spanTextColor = spanTextColor
    		}
    
    		abstract fun onSpanStyled(ds: TextPaint?)
    	}
    
    	/* This stores the click listener for a pattern item, used to handle clicks to a particular category of spans */
    	interface SpannableClickedListener {
    		fun onSpanClicked(text: String?)
    	}
    
    	/* This is the custom clickable span class used
           to handle user clicks to our pattern spans
           applying the styles and invoking click listener.
         */
    	inner class StyledClickableSpan(var item: SpannablePatternItem) : ClickableSpan() {
    		override fun updateDrawState(ds: TextPaint) {
    			if (item.styles != null) {
    				item.styles!!.onSpanStyled(ds)
    			}
    			super.updateDrawState(ds)
    		}
    
    		override fun onClick(widget: View) {
    			if (item.listener != null) {
    				val tv = widget as TextView
    				val span = tv.text as Spanned
    				val start = span.getSpanStart(this)
    				val end = span.getSpanEnd(this)
    				val text = span.subSequence(start, end)
    				item.listener!!.onSpanClicked(text.toString())
    			}
    			widget.invalidate()
    		}
    	}
    
    	/* These are the `addPattern` overloaded signatures */
    	// Each allows us to add a span pattern with different arguments
    	fun addPattern(pattern: Pattern, spanStyles: SpannableStyleListener?, listener: SpannableClickedListener?): PatternEditableBuilder {
    		patterns.add(SpannablePatternItem(pattern, spanStyles, listener))
    		return this
    	}
    
    	fun addPattern(pattern: Pattern, spanStyles: SpannableStyleListener?): PatternEditableBuilder {
    		addPattern(pattern, spanStyles, null)
    		return this
    	}
    
    	fun addPattern(pattern: Pattern): PatternEditableBuilder {
    		addPattern(pattern, null, null)
    		return this
    	}
    
    	fun addPattern(pattern: Pattern, textColor: Int): PatternEditableBuilder {
    		addPattern(pattern, textColor, null)
    		return this
    	}
    
    	fun addPattern(pattern: Pattern, textColor: Int, listener: SpannableClickedListener?): PatternEditableBuilder {
    		val styles: SpannableStyleListener = object : SpannableStyleListener(textColor) {
    
    			override fun onSpanStyled(ds: TextPaint?) {
    				ds?.linkColor = spanTextColor
    			}
    		}
    		addPattern(pattern, styles, listener)
    		return this
    	}
    
    	fun addPattern(pattern: Pattern, listener: SpannableClickedListener?): PatternEditableBuilder {
    		addPattern(pattern, null, listener)
    		return this
    	}
    
    	/* BUILDER METHODS */
    	// This builds the pattern span and applies to a TextView
    	fun into(textView: TextView) {
    		val result = build(textView.text)
    		textView.text = result
    		textView.movementMethod = LinkMovementMethod.getInstance()
    	}
    
    	// This builds the pattern span into a `SpannableStringBuilder`
    	// Requires a CharSequence to be passed in to be applied to
    	fun build(editable: CharSequence?): SpannableStringBuilder {
    		val ssb = SpannableStringBuilder(editable)
    		for (item in patterns) {
    			val matcher = item.pattern.matcher(ssb)
    			while (matcher.find()) {
    				val start = matcher.start()
    				val end = matcher.end()
    				val url = StyledClickableSpan(item)
    				ssb.setSpan(url, start, end, 0)
    			}
    		}
    		return ssb
    	}
    
    }
    
  • Then, add below code in MainActivty.kt file –

            // Style clickable spans based on pattern
            PatternEditableBuilder().addPattern(Pattern.compile("\\@(\\w+)"), Color.BLUE,
                    object : PatternEditableBuilder.SpannableClickedListener {
                        override fun onSpanClicked(text: String?) {
                            Toast.makeText(this@MainActivity, "Clicked on: $text",
                                    Toast.LENGTH_SHORT).show()
                        }
                    }).into(binding.textView)
    

Making text scrollable in TextView

Follow steps below to make text scrollable in textView if text is too long –

  • Use attribute android:scrollbars=”vertical” in Textview in xml file (i.e. in activity_main.xml file).
  • Then, write below code in MainActivity.kt file –
    binding.textView.movementMethod = ScrollingMovementMethod()
    
  • Now, run app. We will see text as scrollable text if it is too long and go outside screen

That’s it.

Thus, we have seen what is textView, how can we use android textview using Kotlin ? etc. We also went through different attributes of android textview.

Leave a Reply