LoginSignup
1
1

More than 3 years have passed since last update.

TextViewをHTMLのように下線を引いたり着色したりする

Last updated at Posted at 2020-09-13

android.core.textSpannableStringBuilder拡張関数を見つけたので使ってみる

また、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

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