2

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.

6
  • As an alternative you can give a dedicated button to select all text Commented Feb 17, 2020 at 8:19
  • @RahulGaur Yes, but I have a multilines EditText, so I want to select only one part of the text... Commented Feb 17, 2020 at 8:25
  • You can modify this, if you want to select only the first line, you can find the position where return is Commented Feb 17, 2020 at 8:29
  • But how can I select the word where the user does a long click ? Commented Feb 17, 2020 at 8:43
  • Please have a look at this answer on how to get cursor position Commented Feb 17, 2020 at 8:46

1 Answer 1

2
+50

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thank you for your answer ! I've tried to use openContextMenu but nothing happens... With the start/end points of cursor, can I show anchors ?
Thank you it's perfect ! I can even remove the postDelayed to just keep performLongClick and setSelection

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.