Skip to content

Instantly share code, notes, and snippets.

@Popalay
Created July 23, 2019 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Popalay/c8e7a732dc3e743dc836a5fcd336e9d1 to your computer and use it in GitHub Desktop.
Save Popalay/c8e7a732dc3e743dc836a5fcd336e9d1 to your computer and use it in GitHub Desktop.
Set un selectable part of text:
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