Home > other >  Is it possible to get value of clicked Text using Modifier.clickable?
Is it possible to get value of clicked Text using Modifier.clickable?

Time:09-12

This is my scenario, I need to get text value of clicked text:

@Composable
fun keyboard(){
    val letters: Array<Pair<String, String>> = letterMap.toList().toTypedArray();
    val txtModifier = Modifier
        .clickable(onClick = { btnTapAction( /* send a letter */ ) })
    for(i in 0..3)
        Row(){
            for(j in (i*8)..(i*8 7))
                if (j<30)
                    Text(letters[j].first, txtModifier)
        }
}

I have 30 Text's, each containing one cyrillic letter, they act like keyboard buttons, and I want to send clicked letter to function btnTapAction() which handles entered letters.

I have looked at documentation and I could not find a way to do it, but I hope it can be done?

CodePudding user response:

If you wish to return value of clicked item create a separate Composable using state-hoisting

@Composable
fun Keyboard(){
    val letters: Array<Pair<String, String>> = letterMap.toList().toTypedArray();
    val txtModifier = Modifier// You can do some styling here such as rounded shape, etc

    for(i in 0..3)
        Row(){
            for(j in (i*8)..(i*8 7))
                if (j<30)
                    Letter( txtModifier, letters[j].first){char:String->
                        // You can pass this letter from keyboard to parent Composable using another callback or process here
                    }
        }
}


@Composable
private fun Letter(modifier: Modifier = Modifier, char: String, onClick: (String) -> Unit) {
    Text(text = char,
        modifier = modifier.clickable {
            onClick(char)
        }
    )
}

Edit

Initial question was like a question to get position of a letter in a Text, you wish to get position of any character inside a Text you can use answer below

You can use ClickableText Composable to get position of click

val context = LocalContext.current
val text = "Some clickable text"

ClickableText(

    text = buildAnnotatedString {
        append(text)
    },
    onClick = { position: Int ->
        Toast.makeText(
            context,
            text.substring(startIndex = 0, endIndex = position),
            Toast.LENGTH_SHORT
        ).show()
    }
)
  • Related