Yes, I know how to do it =) just do it:
Copy the helper class:
class SelectionSpanWatcher(
private val listener: OnChangeSelectionListener
) : SpanWatcher {
override fun onSpanAdded(text: Spannable?, what: Any?, start: Int, end: Int) {
/* do nothing */
}
override fun onSpanRemoved(text: Spannable?, what: Any?, start: Int, end: Int) {
/* do nothing */
}
override fun onSpanChanged(text: Spannable?, what: Any?, oStart: Int, oEnd: Int, nStart: Int, nEnd: Int) {
when (what) {
SELECTION_START -> listener.onSelectionChanged(Selection.START, oStart, oEnd, nStart, nEnd)
SELECTION_END -> listener.onSelectionChanged(Selection.END, oStart, oEnd, nStart, nEnd)
}
}
enum class Selection {
START,
END
}
fun interface OnChangeSelectionListener {
fun onSelectionChanged(selection: Selection, oStart: Int, oEnd: Int, nStart: Int, nEnd: Int)
}
}
Then copy extension method:
fun Editable.setOnSelectionChangedListener(listener: OnChangeSelectionListener?) {
getSpans(0, length, SelectionSpanWatcher::class.java)
.forEach { span -> removeSpan(span) }
if (listener != null) {
setSpan(SelectionSpanWatcher(listener), 0, length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
}
}
Then use the copied code as follows (used androidx.core.widget.addTextChangedListener
from android-ktx
):
editText.addTextChangedListener(afterTextChanged = { editable ->
editable?.setOnSelectionChangedListener { _, _, _, _, _ ->
editText.postOnAnimation {
editText.setSelection(editText.text.length)
}
}
})