Android EditText listener for cursor position change
Just subclass or extend the class EditText and add the following code to the newly create class:
@Override
protected void onSelectionChanged(int selStart, int selEnd) {
// Do ur task here.
}
Don't forget to add constructors to the subclass. :)
You can actually listen to selection changes without subclassing an EditText
. It's a little more complicated but still manageable. To do it you need to add a SpanWatcher
to a text and handle changes of selection spans.
final SpanWatcher watcher = new SpanWatcher() {
@Override
public void onSpanAdded(final Spannable text, final Object what,
final int start, final int end) {
// Nothing here.
}
@Override
public void onSpanRemoved(final Spannable text, final Object what,
final int start, final int end) {
// Nothing here.
}
@Override
public void onSpanChanged(final Spannable text, final Object what,
final int ostart, final int oend, final int nstart, final int nend) {
if (what == Selection.SELECTION_START) {
// Selection start changed from ostart to nstart.
} else if (what == Selection.SELECTION_END) {
// Selection end changed from ostart to nstart.
}
}
};
editText.getText().setSpan(watcher, 0, 0, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
I debugged a related problem across different versions of Android (feel free to comment on your findings and I'll add them to the list).
Summary of findings:
4.1.6 (Samsung device)
onSelectionChanged()
gets called on TEXT EDITS only.
4.0.6 (HTC Device)
4.0.4 (reported by user Arch1tect on Samsung Note 1 device)
onSelectionChanged()
gets called on cursor changes (clicks, moves etc) but NOT on Text Edits.
In the cases above where you are not informed of the section changes (text edits in some versions of Android), you will have to do that using a TextWatcher
, for example in the afterTextChanged()
method.
if anyone is still looking for a solution that does not Subclass the EditText
:
(Code is in kotlin)
editText.setAccessibilityDelegate(object : View.AccessibilityDelegate() {
override fun sendAccessibilityEvent(host: View?, eventType: Int) {
super.sendAccessibilityEvent(host, eventType)
if (eventType == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED){
// here you can access selection of the editText
// with `editText.selectionStart`
// and `editText.selectionEnd``
}
}
})