Kotlin Android – Selectable Text in TextView

To enable text in TextView for selection, set android:textIsSelectable attribute to “true” for the TextView widget in layout XML file.

</>
Copy
    <TextView
        ...
        android:textIsSelectable="true" />

A behavior of selectable text in TextView would look like as shown in the following screenshot.

Kotlin Android - Selectable Text in TextView

Example

In this example, we will create an Android Application with a TextView, and make the text in the TextView selectable.

Create an Android Application with an Empty Activity.

In the main activity layout file, create a TextView as shown in the following code.

activity_main.xml

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textIsSelectable="true"
        android:textSize="30sp"
        android:padding="20sp"
        android:text="Hello World" />

</LinearLayout>

No changes are required in MainActivity.kt file.

MainActivity.kt

</>
Copy
package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

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

Run this Android Application and you should get the TextView displayed with text enabled for selection.

Kotlin Android - Selectable Text in TextView

Double tap or long press on the text of TextView and a selection with options appears as shown in the following screenshot.

Kotlin Android - Selectable Text in TextView

Conclusion

In this Kotlin Android Tutorial, we learned how to enable text in TextView for selection.