You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose实现点击单词弹出Duolingo式Tooltip

在Jetpack Compose中实现点击单词弹出Tooltip(仿Duolingo效果)

我正尝试在Jetpack Compose应用中添加一项功能:当用户点击某个单词时,在该单词的上方/下方弹出tooltip,效果参考Duolingo(点击单词后,单词上方会出现悬浮的解释提示框)。

目前我已实现了带点击交互的AnnotatedString,点击单词时可以打印该单词。以下是相关代码:

生成AnnotatedString的代码

val input = // 获取用户输入的字符串
val words = input.parseInput() // 将字符串拆分为单词和空格的列表(例如 "Hello world" -> ["Hello", " ", "world"])
data class AnnotatedWord(val word: String, val tag: String)
val annotatedWords = mutableListOf<AnnotatedWord>()
var wordIndex = 0
val annotatedString = buildAnnotatedString {
    words.forEach { word ->
        if (word == " ") {
            append(word)
            continue
        }
        val tag = "${word}:${wordIndex++}"
        pushStringAnnotation(tag = tag, annotation = tag)
        withStyle(style = SpanStyle(textDecoration = TextDecoration.Underline)) {
            append(word)
        }
        pop()
        annotatedWords.add(AnnotatedWord(word, tag))
    }
}

带点击监听的展示代码

ClickableText(
    text = annotatedString,
    onClick = { index ->
        val annotation = annotatedString.getStringAnnotations(start = index, end = index).firstOrNull()
        if (annotation != null) {
            val tag = annotation.tag
            val matchingWord = annotatedWords.find { it.tag == tag }
            println(matchingWord?.word)
        }
    }
)

这段代码运行正常:生成的字符串中每个单词都带有下划线,点击单词可打印该单词。但我在实现tooltip部分遇到了困难——我原本打算将ClickableText嵌套在Box中,通过Modifier.offset()将tooltip定位到单词上方,但不知道如何获取目标单词的偏移量,更不清楚如何把这个偏移量传递给Composable。

内容的提问来源于stack exchange,提问作者ichen2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 10:33:35