android Jetpack在一个字段中组合创建ClickableText列表

ewm0tg9j  于 2023-03-16  发布在  Android
关注(0)|答案(1)|浏览(123)

我有代码实现的ClickableText与下划线文本。

Row(
   modifier = Modifier
         .fillMaxWidth()
         .height(IntrinsicSize.Min)
         .padding(5.dp),
            verticalAlignment = Alignment.CenterVertically
   ) {
          Text(
                text = "From",
                fontWeight = FontWeight.Black
          )
          ClickableAddress(emailAddress = addressesFrom)
}

@Composable
fun ClickableAddress(
    emailAddress: Array<EmailAddress?>
) {
    for (address in emailAddress) {
        address?.let { CreateUnderlineEmail(it) }?.let {
            ClickableText(
                text = it,
                onClick = {
                    /*TODO*/
                }
            )
        }
    }
}

@Composable
private fun CreateUnderlineEmail(address: EmailAddress): AnnotatedString {
    return buildAnnotatedString {
        if (address != null) {
            append(address.name + " <")
            withStyle(
                style = SpanStyle(
                    textDecoration = TextDecoration.Underline
                ),
            ) {
                append(address.address)
            }
            append("> ")
        }
    }
}

我怎样才能实现与电子邮件地址列表的文本字段和每一封电子邮件必须点击?
我的代码创建的ClickableText不像行,而是作为单独的字段。

n8ghc7c1

n8ghc7c11#

通过addStringAnnotation找到这样的解决方案

@Composable
fun ClickableAddress(
    emailAddress: Array<EmailAddress?>
) {
    val underlineTExt = CreateUnderlineEmail(address = emailAddress)
    ClickableText(
        text = underlineTExt,
        onClick = {

            underlineTExt.getStringAnnotations("address", it, it)
                .firstOrNull()?.let { stringAnnotation ->
                    /*TODO*/
                }
        }
    )
}

@Composable
private fun CreateUnderlineEmail(address: Array<EmailAddress?>): AnnotatedString {
    return buildAnnotatedString {
        for (address in address) {
            if (address != null) {
                addStringAnnotation(
                    tag = "address",
                    annotation = address.address,
                    start = this.toString().indexOf(address.address), // something like
                    end = this.toString().indexOf(address.address),
                )
                append(address.personal + " <")
                withStyle(
                    style = SpanStyle(
                        textDecoration = TextDecoration.Underline
                    ),
                ) {
                    append(address.address)
                }
                append("> ")
            }

        }
    }
}

相关问题