How to select a word on long press in EditText?

Viewed 120

I use EditText and I want to allow users to select text when they long press a word. For some devices it works perfectly, but for others long press doesn't select word.

For exemple, for some devices, when I long press the EditText, that just show cursor. To select I have to press again, then select all, then move cursors...

How can I select the pressed word on a long press ?

SOLUTION

According to suggestions, I have created an extension for EditText, which select the word with the current selection :

fun EditText.selectCurrentWord() {
    val textSpan = text
    val selection = selectionStart
    val pattern = Pattern.compile("\\w+")
    val matcher = pattern.matcher(textSpan)
    var start: Int
    var end: Int

    while (matcher.find()) {
        start = matcher.start()
        end = matcher.end()

        if (selection in start..end) {
            setSelection(start, end)
            break
        }
    }

    performLongClick()
}

Thank you all !

0 Answers
Related