1
0

JetpackComposeで指定した文字列の色を変更する

Last updated at Posted at 2024-03-11

はじめに

どうもこんにちは、最近Kotlin始めました。普段はUnityを触っています。
今回はテキストフィールドの一部文字列の色を変更するという処理を書いてみたのでまとめました。

JetpackComposeで文字列の色を変更

テキストフィールドに入力する文字列が一定文字数を超えた場合、超えている分だけ赤くするコードを書きました。

↓こんな感じ↓
image.png

VisualTransformationを使用

VisualTransformationとは簡潔に言うと、Input TextFieldの見た目を変更するときに使用するインターフェイスです。1
このインターフェイスを継承したクラスをTextField関数の引数に持たせ、InputFieldの見た目を変更することができます。

手順① テキストフィールドの一部配色を変更するクラスを用意

それではVisualTransformationを継承したクラスを作成します。
ドン!

class ColorsTransformation() : VisualTransformation {
    override fun filter(text: AnnotatedString): TransformedText {
        return TransformedText(
            SetOverLimitTextColor(text.toString()),
            OffsetMapping.Identity
        )
    }

    // 文字数制限をオーバーしている文字だけ色を変更する
    fun SetOverLimitTextColor(text: String): AnnotatedString {
        // 文字が指定の文字数より少なければ処理は行わない
        if (text.length < 150) {
            return AnnotatedString(text);
        }

        var first = text.substring(0, 150) // 0 ~ 150のindexまでの文字を抽出
        var last = text.substring(150, text.length) // 150 ~ 最後の文字列を抽出

        var result = buildAnnotatedString {
            append(first)
            withStyle(SpanStyle(color = Red)) {
                append(last)
            }
        }
        return result;
    }
}

ここでは、filter関数2をオーバーライドしています。filterは任意のtextの見た目を変更できます。
戻り値のTransformedTextには以下の情報を保持しています。

  • Annotating …変換後のテキストのスタイルの情報3
  • OffsetMapping…変換後の文字に対するオフセットの設定4

手順②TextFieldに実際に適用する

手順①で作ったクラスを呼び出して、テキストフィールドの見た目に適用させるだけ

TextField(
            visualTransformation = ColorsTransformation(),
            
            modifier = Modifier
                    .padding(vertical = 4.dp, horizontal = 4.dp),
            .
            .
            .

        )

おわりに

おお!ここC#と同じ!違う!とかとても新鮮でした

参考

  1. VisualTransformation

  2. Change the visual output of given text.

  3. The basic data structure of text with multiple styles.

  4. Provides bidirectional offset mapping between original and transformed text.

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0