0

I want to select text (not all) when user clicks on it.

final EditText field = (EditText) findViewById(R.id.edittext); field.setText("BlaBlaBlaBlaBlaBlaBlaBlaBla"); field.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { field.setSelection(0, 10); } } }); 

But text isn't selected. The cursor appears at the point of click.

How can I do this?

Updated:

Why simple method setSelection(start, end) in "Hello World" app doesn't work?

4
  • how much text do you want to select? Commented Mar 21, 2017 at 14:28
  • @nandsito, I want to select any number of characters, but not all text. In above example I select from 0 to 10 (length of text is more than 10 characters). Commented Mar 21, 2017 at 14:38
  • do you care for other gestures, e.g. double tap, long press, fling etc. or there is no problem in getting rid of them? Commented Mar 21, 2017 at 15:07
  • @nandsito yes, I do. I want the user to be able to put the cursor and edit any part of the text, but the first click always highlights the amount of text I need Commented Mar 21, 2017 at 15:34

1 Answer 1

1

I found incredible solution. If I set android:selectAllOnFocus="true" or programmatically.

And simple snippet code works fine:

final EditText field = (EditText) findViewById(R.id.edittext); field.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { field.setSelection(0, 10); } } }); 

But if I remove android:selectAllOnFocus="true" or set false - everything breaks down.

I don't know why!!

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.