SpannableStringBuilder
- ハイライトしたい文字列とTextViewに入れる全体の文字列を定義
-
SpannableStringBuilder#setSpan
でClickableSpan()
を呼び出し- onClickにてIntentを指定
- updateDrawStateにて色を指定
private fun createLinkSpannable(): SpannableStringBuilder {
val highLightText = getString(R.string.high_light_text)
val introductionText = getString(R.string.introduction_text)
val spannableTextBuilder = SpannableStringBuilder(introductionText)
val startPos = introductionText.indexOf(highLightText)
return spannableTextBuilder.apply {
setSpan(object : ClickableSpan() {
override fun onClick(view: View) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(URL))
view.context.startActivity(intent)
}
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.color = ContextCompat.getColor(this@MainActivity, R.color.colorAccent)
}
}, startPos, startPos + highLightText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
TextView
- textに上記のSpannableを指定
- movementMethodを指定
MainActivity.kt
link_text.apply {
text = createLinkSpannable()
movementMethod = LinkMovementMethod.getInstance()
}
レポジトリはこちら