Всем привет. Требуется создать TextView в котором можно будет выбрать лишь одно слово. Также будет фильтр не позволяющий выбрать слово с определенными запрещенными символами. Помимо этого текст скопировать будет нельзя. При выделение должно быть кастомное меню с кнопками. Скажите, есть ли в андроиде такое? Может кто использовал библиотеку с подобным функционалом? Подскажите куда копать, делать кастомный TextView?
1 ответ
Вообщем, дизайн сменили и сошлось все на создании кастомного LinkMovementMethod
. Взял код из библиотеки BetterLinkMovementMethod
и переписал под себя
class BetterLinkMovementMethod private constructor() : LinkMovementMethod() {
var onLinkClickListener: OnLinkClickListener? = null
var wordSelectionListener: OnWordSelectionListener? = null
private var touchDownX = 0
private var touchDownY = 0
private val touchedLineBounds = RectF()
private var isUrlHighlighted: Boolean = false
private var clickableSpanUnderTouchOnActionDown: ClickableSpan? = null
private var activeTextViewHashcode: Int = 0
private var ongoingLongPressTimer: LongPressTimer? = null
private var wasLongPressRegistered: Boolean = false
interface OnLinkClickListener {
fun onClick(textView: TextView, url: String): Boolean
}
interface OnWordSelectionListener {
fun onWordSelected(word: String)
}
override fun onTouchEvent(textView: TextView, text: Spannable, event: MotionEvent): Boolean {
if (activeTextViewHashcode != textView.hashCode()) {
activeTextViewHashcode = textView.hashCode()
textView.autoLinkMask = 0
}
val clickableSpanUnderTouch = findClickableSpanUnderTouch(textView, text, event)
if (event.action == MotionEvent.ACTION_DOWN) {
clickableSpanUnderTouchOnActionDown = clickableSpanUnderTouch
}
val touchOnText = clickableSpanUnderTouchOnActionDown == null
var x = event.x.toInt()
var y = event.y.toInt()
x -= textView.totalPaddingLeft
y -= textView.totalPaddingTop
x += textView.scrollX
y += textView.scrollY
when (event.action) {
MotionEvent.ACTION_DOWN -> {
if (clickableSpanUnderTouch != null) {
highlightUrl(textView, clickableSpanUnderTouch, text)
}
if (touchOnText) {
touchDownX = x
touchDownY = y
val longClickListener = object : LongPressTimer.OnTimerReachedListener {
override fun onTimerReached() {
wasLongPressRegistered = true
val layout = textView.layout
val line = layout.getLineForVertical(touchDownY)
val offset = layout.getOffsetForHorizontal(line, touchDownX.toFloat())
if (offset <= textView.text.lastIndex &&
!Character.isSpaceChar(textView.text[offset])) {
textView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
val before = textView.text.subSequence(0, offset)
val after = textView.text.subSequence(offset, textView.text.lastIndex)
val wordStart = before.indexOfLast { !it.isLetter() } + 1
var wordEnd = after.indexOfFirst { !it.isLetter() }
if (wordEnd == -1) wordEnd = textView.text.lastIndex
else wordEnd += offset
val word = textView.text.subSequence(wordStart, wordEnd).toString()
if (word.isNotEmpty()) {
wordSelectionListener?.onWordSelected(word)
}
}
}
}
startTimerForRegisteringLongClick(textView, longClickListener)
}
return touchOnText
}
MotionEvent.ACTION_UP -> {
if (!wasLongPressRegistered && !touchOnText && clickableSpanUnderTouch === clickableSpanUnderTouchOnActionDown) {
dispatchUrlClick(textView, clickableSpanUnderTouch!!)
}
cleanupOnTouchUp(textView)
return touchOnText
}
MotionEvent.ACTION_CANCEL -> {
cleanupOnTouchUp(textView)
return false
}
MotionEvent.ACTION_MOVE -> {
if (event.x !in touchDownX - 5..touchDownX + 5 || event.y !in touchDownY - 5..touchDownY + 5) {
removeLongPressCallback(textView)
}
return touchOnText
}
else -> return false
}
}
private fun cleanupOnTouchUp(textView: TextView) {
wasLongPressRegistered = false
clickableSpanUnderTouchOnActionDown = null
removeUrlHighlightColor(textView)
removeLongPressCallback(textView)
}
private fun findClickableSpanUnderTouch(textView: TextView, text: Spannable, event: MotionEvent): ClickableSpan? {
var touchX = event.x.toInt()
var touchY = event.y.toInt()
touchX -= textView.totalPaddingLeft
touchY -= textView.totalPaddingTop
touchX += textView.scrollX
touchY += textView.scrollY
val layout = textView.layout
val touchedLine = layout.getLineForVertical(touchY)
val touchOffset = layout.getOffsetForHorizontal(touchedLine, touchX.toFloat())
touchedLineBounds.left = layout.getLineLeft(touchedLine)
touchedLineBounds.top = layout.getLineTop(touchedLine).toFloat()
touchedLineBounds.right = layout.getLineWidth(touchedLine) + touchedLineBounds.left
touchedLineBounds.bottom = layout.getLineBottom(touchedLine).toFloat()
if (touchedLineBounds.contains(touchX.toFloat(), touchY.toFloat())) {
val spans = text.getSpans(touchOffset, touchOffset, ClickableSpan::class.java)
for (span in spans) {
if (span is ClickableSpan) {
return span
}
}
return null
} else {
return null
}
}
private fun highlightUrl(textView: TextView, clickableSpan: ClickableSpan, text: Spannable) {
if (isUrlHighlighted) {
return
}
isUrlHighlighted = true
val spanStart = text.getSpanStart(clickableSpan)
val spanEnd = text.getSpanEnd(clickableSpan)
val highlightSpan = BackgroundColorSpan(textView.highlightColor)
text.setSpan(highlightSpan, spanStart, spanEnd, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
textView.setTag(R.id.movementmethod_highlight_background_span, highlightSpan)
Selection.setSelection(text, spanStart, spanEnd)
}
private fun removeUrlHighlightColor(textView: TextView) {
if (!isUrlHighlighted) {
return
}
isUrlHighlighted = false
val text = textView.text as Spannable
val highlightSpan = textView.getTag(R.id.movementmethod_highlight_background_span) as BackgroundColorSpan
text.removeSpan(highlightSpan)
Selection.removeSelection(text)
}
private fun startTimerForRegisteringLongClick(textView: TextView, longClickListener: LongPressTimer.OnTimerReachedListener) {
ongoingLongPressTimer = LongPressTimer()
ongoingLongPressTimer!!.setOnTimerReachedListener(longClickListener)
textView.postDelayed(ongoingLongPressTimer, ViewConfiguration.getLongPressTimeout().toLong())
}
private fun removeLongPressCallback(textView: TextView) {
if (ongoingLongPressTimer != null) {
textView.removeCallbacks(ongoingLongPressTimer)
ongoingLongPressTimer = null
}
}
private fun dispatchUrlClick(textView: TextView, clickableSpan: ClickableSpan) {
val clickableSpanWithText = ClickableSpanWithText.ofSpan(textView, clickableSpan)
val handled = onLinkClickListener != null && onLinkClickListener!!.onClick(textView, clickableSpanWithText.text)
if (!handled) {
clickableSpanWithText.span.onClick(textView)
}
}
class LongPressTimer : Runnable {
private var onTimerReachedListener: OnTimerReachedListener? = null
interface OnTimerReachedListener {
fun onTimerReached()
}
override fun run() {
onTimerReachedListener!!.onTimerReached()
}
fun setOnTimerReachedListener(listener: OnTimerReachedListener) {
onTimerReachedListener = listener
}
}
class ClickableSpanWithText private constructor(val span: ClickableSpan, val text: String) {
companion object {
fun ofSpan(textView: TextView, span: ClickableSpan): ClickableSpanWithText {
val s = textView.text as Spanned
val text: String
if (span is URLSpan) {
text = span.url
} else {
val start = s.getSpanStart(span)
val end = s.getSpanEnd(span)
text = s.subSequence(start, end).toString()
}
return ClickableSpanWithText(span, text)
}
}
}
companion object {
fun newInstance(): BetterLinkMovementMethod {
return BetterLinkMovementMethod()
}
}
}
on(Long)Click
+SpannableString
+PopupWindow
. Не знаю, как правильно собрать эту конструкцию (в основном, как отслеживать позицию/слово клика), но смотрел бы в эту сторону