Jetpack Compose のテキストの最後の単語にアイコンを追加する 質問する

Jetpack Compose のテキストの最後の単語にアイコンを追加する 質問する

動的な複数行のテキストと、最後の行の末尾にアイコンを表示したいです。このアイコンはアニメーション化できます。いくつかの方法を試しましたが、まだ成功していません。どうすればよいでしょうか?

私のレイアウトと同じアイデアを持つサンプルビュー

ここに画像の説明を入力してください

ベストアンサー1

Textコンポーザブルでは、inlineContentテキストの特定の範囲を置き換えるタグのマップを定義します。これは、テキストレイアウトにコンポーザブルを挿入するために使用されます。
次に、Placeholderテキストレイアウトでスペースを予約できます。

何かのようなもの:

val myId = "inlineContent"
val text = buildAnnotatedString {
    append("Where do you like to go?")
    // Append a placeholder string "[icon]" and attach an annotation "inlineContent" on it.
    appendInlineContent(myId, "[icon]")
}

val inlineContent = mapOf(
    Pair(
        // This tells the [CoreText] to replace the placeholder string "[icon]" by
        // the composable given in the [InlineTextContent] object.
        myId,
        InlineTextContent(
            // Placeholder tells text layout the expected size and vertical alignment of
            // children composable.
            Placeholder(
                width = 12.sp,
                height = 12.sp,
                placeholderVerticalAlign = PlaceholderVerticalAlign.AboveBaseline
            )
        ) {
            // This Icon will fill maximum size, which is specified by the [Placeholder]
            // above. Notice the width and height in [Placeholder] are specified in TextUnit,
            // and are converted into pixel by text layout.
            
            Icon(Icons.Filled.Face,"",tint = Color.Red)
        }
    )
)

Text(text = text,
     modifier = Modifier.width(100.dp),
     inlineContent = inlineContent)

ここに画像の説明を入力してください

コンポーザブルなので、お好みのアニメーションを使用できます。

ほんの一例です:

var blue by remember { mutableStateOf(false) }
val color by animateColorAsState(if (blue) Blue else Red,
    animationSpec = tween(
        durationMillis = 3000
    ))

アイコンを

Icon(Icons.Filled.Face,"", tint = color)

ここに画像の説明を入力してください

おすすめ記事