例として、Hello Wolrd!
のWorld
部分を装飾します。
文中の文字色・太さ・大きさ・下線・上付き文字・下付き文字
strings.xml
<string name="text1">Hello <font color="red">World</font>!</string>
<string name="text2">Hello <b>World</b>!</string>
<string name="text3">Hello <big>World</big>!</string>
<string name="text4">Hello <font size="40">World</font>!</string>
<string name="text5">Hello <u>World</u>!</string>
<string name="text6">Hello <sup>World</sup>!</string>
<string name="text7">Hello <sub>World</sub>!</string>
spで大きさ指定
Hello World!
の6番目から11番目の文字を大きくする
style.xml
<style name="Text8">
<item name="android:textSize">20sp</item>
</style>
MainActivity.kt
binding.text8.text = SpannableString(getString(R.string.text8)).apply {
setSpan(
TextAppearanceSpan(this@MainActivity, R.style.Text8),
6,
11,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
URLリンク
strings.xml
<string name="text9">Hello <a href="https://www.example.com">World</a>!</string>
MainActivity.kt
binding.text9.movementMethod = LinkMovementMethod.getInstance()
URLリンク(下線なし)
MainActivity.kt
val clickableSpan = object : ClickableSpan() {
override fun onClick(p0: View) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://www.example.com")))
}
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.color = ContextCompat.getColor(this@MainActivity, R.color.design_default_color_primary)
ds.isUnderlineText = false
}
}
binding.text10.text = SpannableString(getString(R.string.text10)).apply {
setSpan(clickableSpan, 6, 11, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
}
binding.text10.movementMethod = LinkMovementMethod.getInstance()