9
4

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 5 years have passed since last update.

TextViewの一部にリンクをつける

Posted at

SpannableStringBuilder

  • ハイライトしたい文字列とTextViewに入れる全体の文字列を定義
  • SpannableStringBuilder#setSpanClickableSpan()を呼び出し
    • 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()
}

こんな感じになります
スクリーンショット 2019-03-17 23.45.01.png

レポジトリはこちら

9
4
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
9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?