2

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 !

Ady
  • 230
  • 3
  • 16
  • 2
    https://stackoverflow.com/questions/8612652/select-a-word-on-a-tap-in-textview-edittext – Atiq Jun 12 '20 at 13:30
  • 1
    call `editText.setSelection(pos)`on long click maybe? First you should put the cursor where you should start (position) and then call `setSelection(endPos)` – mirsaidoff Jun 16 '20 at 06:29

0 Answers0