LoginSignup
9
1

【Jetpack Compose】特定の文字だけ色を変える

Last updated at Posted at 2023-11-30

はじめに

この記事はand factory.inc Advent Calendar 2023 1日目の記事です。

and factoryでandroidエンジニアをやっていますが、
今年学んだ小さいチップスを共有したいと思います。

特定の文字だけ色を変えるComposable

Jetpack Composeネタです。
こういうことしたいケースは稀ですが検索候補でヒットした文字列だけ色を変えるとかで使えそうですね。

スクリーンショット 2023-07-06 10.54.15.png

とりあえずコピペしよう

サンプルは赤色ですが、上記のプレビュー画像はオレンジ色の独自のカラーを指定しています。

// 指定文字列を指定色に変える拡張関数
fun String.colorize(colorizeString: String, color: Color): AnnotatedString {
    val modifiedString = this.replace(colorizeString, "|||$colorizeString|||")
    val resultArrayIncludingSplit = modifiedString.split("|||").filter { it.isNotEmpty() }
    return buildAnnotatedString {
        resultArrayIncludingSplit.forEach {
            if (it == colorizeString) {
                withStyle(
                    style = SpanStyle(color = color),
                ) {
                    append(it)
                }
            } else {
                append(it)
            }
        }
    }
}


// 使用例
@Composable
fun TextColorizer(text: String, filterString: String) {
    Text(
        text.colorize(colorizeString = filterString, color = Color.Red), // 好きな色に変えてください
    )
}

@Preview
@Composable
fun TextColorlizerPreview() {
    TextColorizer("風の谷のナウシカ", "の")
}

具体的には

以下のような流れが実現できるコードです。

  1. 文字列をパースできる形に変換する(この場合|||を入れている)
  2. 文字列|||区切りで配列にパースする
  3. 配列を回して文字列一致するもののスタイルを変更する

おわりに

力技ですが実際に弊社で開発しているマンガアプリで使われています。
ぜひご利用とともに探してみてください。(ヒントはオレンジ色)

明日のAdvent Calendarの記事もお楽しみに:santa:

9
1
1

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
9
1