Android Jetpack Compose – Text Selectable

Android Jetpack Compose – Text Selectable

To make the text in Text composable as selectable in Android Jetpack Compose, you can wrap the Text composable in SelectionContainer composable.

The following is a sample code snippet of how you wrap Text composable with SelectionContainer composable.

SelectionContainer {
    Text(

    )
}

Example

In the following example, we have set the text in Text composable selectable by wrapping the Text composable in a SelectionContainer composable.

MainActivity.kt

package com.example.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.sp
import com.example.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    SelectionContainer {
                        Text(
                            text = "Hello Android\nThis is sample text\nAnd another line",
                            fontSize = 25.sp,
                        )
                    }
                }
            }
        }
    }
}

Screenshot

Android Jetpack Compose - Text Selectable
Text composable with selectable text

Summary

In this tutorial, we have seen how to make the text in Text composable available for selection, in Android Jetpack Compose, using SelectionContainer composable.