Created
July 23, 2019 10:04
-
-
Save Popalay/c8e7a732dc3e743dc836a5fcd336e9d1 to your computer and use it in GitHub Desktop.
Set un selectable part of text:
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.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