Monday, March 1, 2021

jetpack compose - ClickableText example

MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.compose.foundation.text.ClickableText
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        val annotatedText = buildAnnotatedString {
            withStyle(style = SpanStyle(
                color = Color.Red,
                fontSize = 30.sp,
                fontWeight = FontWeight.Bold,
                fontFamily = FontFamily.Monospace,
                background = Color.LightGray,
            )){
                append("Click Me")
            }
        }

        ClickableText(
            text = annotatedText,
            onClick = { offset ->
                Toast.makeText(
                    this,
                    "$offset -th character is clicked",
                    Toast.LENGTH_SHORT
                ).show()
            }
        )
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}