1
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 1 year has passed since last update.

【Android】TextViewのTextの一部だけ大きくする【kotlin】

Posted at

実践

    val textView = findViewById<TextView>(R.id.text_view)
    val spanText = SpannableString(textView.text)
    spanText.setSpan(RelativeSizeSpan(2f), 6, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    textView.text = text

↓xml側でtextSizeを40spでした場合

Screenshot_2023-04-23-21-12-43-75_7775b79a7312c35cfd35e081660950c8.png

説明

SpannableString()内に サイズを変更したい文字列を渡します。
それに対してsetSpan()することで 文字に変化を与えることができます。
第一引数に RelativeSizeSpanで大きさを指定します。
RelativeSizeSpanは 比率に基づいてサイズを変更できるSpanで、上の例ではRelativeSizeSpanはに(2f)を渡すことで ほかの文字の2倍のサイズになっています。
特にテキストのサイズについて指定をしていない場合は、XML上で指定したTextSizeの2倍になります。
第二引数に開始位置 第三引数に終わり位置 (スペースも1文字分としてカウント)

Span内に動的に文字列を追加したい場合 追加した文字にもSpanを含ませたい場合は

Spannable.SPAN_EXCLUSIVE_INCLUSIVE 

含ませない場合は

Spannable.SPAN_EXCLUSIVE_EXCLUSIVE

を第四引数に指定します。

参考

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