iOSでは NSMutableAttributedString
を使いますが、Androidの場合は SpannableStringBuilder
を用いるようです。
この例では以下の装飾を加えています。
target 文字列と一致する部分に
- フォント色を赤色
- フォントを太字
val textView = findViewById<TextView>(R.id.description_textview) val message = textView.text.toString() val target = getString(R.string.auto_renewal) val firstIndex = message.indexOf(target) val endIndex = firstIndex + target.length val color = ResourcesCompat.getColor( applicationContext.resources, R.color.viewfinder_laser, null ) SpannableStringBuilder(message).let { it.setSpan(ForegroundColorSpan(color), firstIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) it.setSpan( StyleSpan(android.graphics.Typeface.BOLD), firstIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) textView.setText(it, TextView.BufferType.SPANNABLE) }