Skip to content

Instantly share code, notes, and snippets.

@Atsumi3
Created November 12, 2019 03:06
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Atsumi3/8937fcde53984764c2a9e03fe2c25c38 to your computer and use it in GitHub Desktop.
文字列をタップした時の制御を楽にする拡張
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ClickableSpan
import android.view.View
import java.util.regex.Pattern
// 格納先のTextViewに以下の設定が必須
// textView.movementMethod = LinkMovementMethod.getInstance()
fun CharSequence.setTextClickListener(regex: String = "", onClick: ((text: String) -> Unit)): SpannableString {
// regexが空だったら自分自身を指定する (テキスト全てがClickableになる)
val targetRegex = if (regex.isEmpty()) {
this as String
} else {
regex
}
val builder = SpannableString(this)
val matcher = Pattern.compile(targetRegex).matcher(this)
while (matcher.find()) {
val start = matcher.start()
val end = matcher.end()
val findText = matcher.group(0)
builder.setSpan(object : ClickableSpan() {
override fun onClick(widget: View) {
onClick(findText)
}
}, start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
}
return builder
}
@Atsumi3
Copy link
Author

Atsumi3 commented Nov 12, 2019

こんな感じで。

binding.textView.movementMethod = LinkMovementMethod.getInstance()
binding.textView.text = "ブラウザで開く".setTextClickListener("ブラウザで開く") { clickedText ->
  Log.d("TextClickListener", clickedText)
  listener?.onTextLinkClick()
}

@Atsumi3
Copy link
Author

Atsumi3 commented Nov 12, 2019

binding.textView.text = "ブラウザで開く".setTextClickListener { clickedText ->
  Log.d("TextClickListener", clickedText)
  listener?.onTextLinkClick()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment