0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TextViewの文字を修飾する

Posted at

ここの文字太字にしてとか言われてやり方を調べるので、自分用のメモ

初級

string.xmlに設定すれば太字とかは簡単に実装できる

    <string name="password">パスワード</string>
    <string name="password_u"><u>パスワード(下線)</u></string>
    <string name="password_b"><b>パスワード(太字)</b></string>
    <string name="password_u_2">一部<u>パスワード</u>(下線)</string>
    <string name="password_b_2">一部<b>パスワード</b>(太字)</string>

device-2020-12-17-141536.png

中級

動的に下線 太字を設定する

        val textN = findViewById<TextView>(R.id.password_n)
        textN.text = getString(R.string.mail)

        val textU = findViewById<TextView>(R.id.password_u)
        textU.text = getString(R.string.password_u)

        val textB = findViewById<TextView>(R.id.password_b)
        textB.text = getString(R.string.password_b)

device-2020-12-17-142204.png

失敗する!!!

全部を太字にする場合

[android:textStyle="bold"]をTextViewのxmlに設定すれば対応可能

android:textStyle="bold"

TextViewに[.typeface = Typeface.DEFAULT_BOLD]でも可能

textB.typeface = Typeface.DEFAULT_BOLD

一部を太字にする場合

SpannableStringBuilder を使えば解決する

        val textB = findViewById<TextView>(R.id.password_b)
        val testPassword = getString(R.string.password_b_2)
        val sb = SpannableStringBuilder(testPassword)
        sb.setSpan(
            StyleSpan(Typeface.BOLD),
            2, //太字開始位置
            testPassword.length - 4, //終了位置
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        textB.text = sb

スクリーンショット 2020-12-17 14.42.45.png

公式ドキュメント
SpannableStringBuilder
Span

これみたら文字色変えたり下線にしたりサイズ大きくしたり色々書いてるよ

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?