android.core.text
にSpannableStringBuilder
の拡張関数を見つけたので使ってみる
また、TextViewの拡張関数としているが、BindingAdapter
でも使えるようにしている。
準備
core-ktx
app/build.gradle にcore-ktx
を追加する
app/build.gradle.kts
implementation("androidx.core:core-ktx:1.5.0-alpha01")
下線
SpannableStringBuilder().underline {}
を使うパターン
/**
* TextViewに下線付きで文字を表示する (SpannableStringBuilder 版)
*/
@BindingAdapter("textWithUnderline")
fun TextView.textWithUnderline(text: String?) {
if (text.isNullOrEmpty()) return
this.text = SpannableStringBuilder().underline {
append(text)
}
}
HtmlCompatを使うパターン
/**
* TextViewに下線付きで文字を表示する(HtmlCompat 版)
*/
@BindingAdapter("textWithUnderline")
fun TextView.textWithUnderline(text: String?) {
text ?: return
this.text = HtmlCompat.fromHtml("<u>$text</u>", HtmlCompat.FROM_HTML_MODE_COMPACT)
}
BindingAdapter で使うとき
app:textWithUnderline
で使える
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
app:textWithUnderline='@{"under line"}'
tools:text="under line"
/>
文字色
SpannableStringBuilder().color() {}
を使うパターン
/**
* TextViewに文字色をつける(SpannableStringBuilder 版)
*/
@BindingAdapter("textWithRedColor2")
fun TextView.textWithRedColor2(text: String?) {
if (text.isNullOrEmpty()) return
val color = ContextCompat.getColor(this@textWithRedColor2.context, R.color.colorAccent)
this.text = SpannableStringBuilder().color(color) { append(text) }
}
HtmlCompatパターン
/**
* TextViewに文字色をつける(HtmlCompat 版)
*/
@BindingAdapter("textWithRedColor")
fun TextView.textWithRedColor(text: String?) {
if (text.isNullOrEmpty()) return
this.text = HtmlCompat.fromHtml("ここは<font color='red'>$text</font>", HtmlCompat.FROM_HTML_MODE_COMPACT)
}
背景色
/**
* 文字のBackgroundに色をつける(SpannableStringBuilder 版)
*/
@BindingAdapter("textWitBackgroundColor")
fun TextView.textWitBackgroundColor(text: String?) {
if (text.isNullOrEmpty()) return
val color = ContextCompat.getColor(this.context, R.color.colorAccent)
this.text = SpannableStringBuilder().backgroundColor(color) {
append(text)
}
}
GitHub
備考
SpannableStringBuilder
で複数パターンの装飾をするにはsetSpan()
を使うとできるはず。
HtmlCompat
はタグを書いて装飾するため、自由度とカスタム製が高そう
Spanの公式ドキュメント
https://developer.android.com/guide/topics/text/spans?hl=ja
SpannableStringBuilderの拡張関数
https://developer.android.com/reference/kotlin/androidx/core/text/package-summary?hl=ja#extension-functions