Last active
July 23, 2019 10:04
-
-
Save Popalay/bee77952319ccac40ac39d4204a0f582 to your computer and use it in GitHub Desktop.
Set unselectable part of text:
This file contains hidden or 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.Selection | |
import android.text.SpanWatcher | |
import android.text.Spannable | |
import kotlin.math.max | |
class UnselectablePrefixSpanWatcher(private val prefix: String) : SpanWatcher { | |
override fun onSpanAdded(text: Spannable, what: Any, start: Int, end: Int) = Unit | |
override fun onSpanRemoved(text: Spannable, what: Any, start: Int, end: Int) = Unit | |
override fun onSpanChanged(text: Spannable, what: Any, ostart: Int, oend: Int, nstart: Int, nend: Int) { | |
if (what == Selection.SELECTION_START) { | |
if (nstart < prefix.length) { | |
val end = max(prefix.length, Selection.getSelectionEnd(text)) | |
Selection.setSelection(text, prefix.length, end) | |
} | |
} else if (what == Selection.SELECTION_END) { | |
val start = max(prefix.length, Selection.getSelectionEnd(text)) | |
val end = max(start, nstart) | |
if (end != nstart) { | |
Selection.setSelection(text, start, end) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
EditText.text.setSpan(UnselectablePrefixSpanWatcher(prefix), 0, 0, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)