Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android EditText - Focus on it and select all text programmatically

Tags:

android

I am new to Android and I am trying to figure out how do I focus on EditText and select all text in it.

Here is the scenario:

  1. User enters user name in EditText

  2. App evaluates it somehow and if user name is not valid, it should automatically focus on User Name Edit text and select all text user has entered previously so user does not have to backspace to delete it all in order to reenter new user name.

Much appreciated,

like image 913
pixel Avatar asked Jul 21 '15 23:07

pixel


3 Answers

I figured it out. Here is what I did.

I have a button user clicks when he enters user name (the positive button on DialogFragment). On button click event, I do this:

editUserName.setSelectAllOnFocus(true);
editUserName.selectAll();

This will focus and select all text in the EditText.

like image 81
pixel Avatar answered Nov 11 '22 08:11

pixel


For selection of all the text of Edittext, you can use

editText.setSelection(0,editText.getText().toString().length());

and if you want to set cursor position you can use

editText.setSelection(position);

like image 29
varotariya vajsi Avatar answered Nov 11 '22 10:11

varotariya vajsi


You can also add android:selectAllOnFocus="true" to the EditText

like image 42
Tgo1014 Avatar answered Nov 11 '22 09:11

Tgo1014