LoginSignup
3
1

More than 1 year has passed since last update.

【Android】TextView内の文中の装飾

Last updated at Posted at 2021-02-18

例として、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()

Screenshot_1613631090.png

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()

Screenshot_1613631090 - コピー.png

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