Created
November 12, 2019 03:06
-
-
Save Atsumi3/8937fcde53984764c2a9e03fe2c25c38 to your computer and use it in GitHub Desktop.
文字列をタップした時の制御を楽にする拡張
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 | |
} |
Author
Atsumi3
commented
Nov 12, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment