Text selection depending on the phone

Ady :

In my app, I have an EditText where the user can select a part of the text. The problem is that the selection behavior is different depending on the phone : with one, the user can select normally, but with another one the user must tap on the text indicator and then tap on "Select All".

How can I set the behavior like the first one as default ? And why the behavior is different between phones ?

Thank you for your answers, have a nice day !

EDIT :

Now I select the word which contains the cursor with this method :

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
        }
    }
}

But now the problem is that cursors at the start and end of selection doesn't appear...

The EditText is selectable and isCursorVisible is set to true.

Rahul Gaur :

You can try using a Button to select the text using

EditText myET = findViewById(R.id.myET);
Button selectBtn = findViewById(R.id.selectBtn);

selectBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        myET.setSelectAllOnFocus(true);
        myET.selectAll();    
    }
});

You can open context menu using

openContextMenu(myET);

You can also get the position of starting and end point of cursor

myET.getSelectionStart();
myET.getSelectionEnd();

Referring answers

  1. Getting cursor position

  2. Select Text programmatically

Update 1

Add this in your button click, this seems to work, but sometimes you have to click 2 times you can tweak this

myET.performLongClick();
myET.setSelection(0, myET.length());

Hope this will help!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=7338&siteId=1