Created
November 12, 2019 03:06
Star
You must be signed in to star a gist
文字列をタップした時の制御を楽にする拡張
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
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
こんな感じで。