TextViewでテキストの一部分の文字色だけを変更しようと思い、調べていたのだけれど、TextAppearanceSpanのサンプル例ばかり出てくる。
確かにアンダーラインや文字のスタイル(Bold)などを指定する場合はstyle用の
XMLを用意するのが筋かもしれないが、ただ色を変えるだけならばちょっと大掛かりすぎるように思える。
また、色のカラーコードをXML外で管理している場合もこれまた億劫だ。
色々調べていくうちに、解決策としてForegroundColorSpanとを使えば良いということが分かった。
単純にコンストラクタに色情報のIntegerを渡すだけで良い。
※ textViewはXMLのレイアウトにR.id.text_viewとしてあらかじめ用意されているものとする
// 〜前段処理〜 TextView textView = findViewById(R.id.text_view); String message = "message"; int spanColor = Color.RED; SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(message); spannableStringBuilder.setSpan(new ForegroundColorSpan(spanColor), 0, 1, 0); textView.setText(spannableStringBuilder.subSequence(0, spannableStringBuilder.length())); // 〜後続処理〜
サンプル(Kotlin):
※ textViewはXMLのレイアウトにR.id.text_viewとしてあらかじめ用意されているものとする
// 〜前段処理〜 val textView: TextView = findViewById(R.id.text_view) val message: String = "message" val spanColor: Int = Color.RED SpannableStringBuilder(message).let { it.setSpan(ForegroundColorSpan(spanColor), 0, 1, 0) textView.text = it.subSequence(0, it.length) } // 〜後続処理〜
これで、messageの出力が先頭の「m」だけ赤くなる。
結果: