Clickable Text in Jetpack Compose

Hello Developers, Welcome to Jetpack Compose tutorials. In this tutorial, We are going to learn Clickable Text in Jetpack Compose Using Kotlin with Android Studio.

Clickable Text in Jetpack Compose

First Open your Android Studio project and Create a Composable Function for Clickable Text

SimpleClickableText Composable Function

@Composable
fun SimpleClickableText() {
    ClickableText(
        text = AnnotatedString("Click Me"),
        onClick = { offset ->
            Log.d("ClickableText", "$offset -th character is clicked.")
        }
    )
}

The complete example code is given below

package com.techpassmaster.jetpackcomposetextandstyles

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.AnnotatedString
import com.techpassmaster.jetpackcomposetextandstyles.ui.theme.JetpackComposeTextAndStylesTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            JetpackComposeTextAndStylesTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    SimpleClickableText()
                }
            }
        }
    }
}

@Composable
fun SimpleClickableText() {
    ClickableText(
        text = AnnotatedString("Click Me"),
        onClick = { offset ->
            Log.d("ClickableText", "$offset -th character is clicked.")
        }
    )
}

After clicking on the text, Check the output in the Logcat

You May Also Like ⇣

Leave a Reply

Your email address will not be published. Required fields are marked *