18

I have a edit text in my app. When the user touches the edit text the whole text should be selected and when he starts typing text should be cleared. An example is browser address bar. Is there any way to do this?Please help me.

Jignesh Ansodariya
  • 12,583
  • 24
  • 81
  • 113
user1767260
  • 1,543
  • 8
  • 26
  • 51

6 Answers6

32

You can select all text in EditText by using

android:selectAllOnFocus and also setSelectAllOnFocus(boolean)

Ram kiran Pachigolla
  • 20,897
  • 15
  • 57
  • 78
  • 1
    Thanks.This selects the text but when I again touch on the edit text to display the keypad, text is not cleared. – user1767260 Nov 21 '12 at 04:57
6

Call EditText.setSelectAllOnFocus(boolean selectAllOnFocus) to select all text on focus.

Set a click listener to your EditText and in onClick call edittext.selectAll();

Ron
  • 24,175
  • 8
  • 56
  • 97
  • Set a click listener to your EditText and in onClick call edittext.selectAll(); – Ron Nov 21 '12 at 06:20
  • Thanks, this is better than the answer, because you might not want your ET to have focus right away when you arrive in the activity. But instead of doing an `onClick` in the XML, I set an `onClickListener` in my ET activity, then put the `selectAll()` method to my ET on its `onClick()` method, and it selects all only when you click it. – Azurespot May 13 '16 at 06:47
3

Add attribute to your main.xml file:

android:selectAllOnFocus="true"

Then all text will be selected and when user type something that will remove it.

Marcin S.
  • 11,161
  • 6
  • 50
  • 63
1

You can use property android:hint instead of android:text and you get what you want wihout special code.

Artyom Kiriliyk
  • 2,513
  • 1
  • 17
  • 21
0

You can select all text in EditText by using android:selectAllOnFocus or setSelectAllOnFocus(boolean).

Set a flag when all text is selected. Then detect a text change by using the addTextChangedListener method on your EditText and make your class implement or define an inner class implementing the TextWatcher class.

In this watcher class method, check the flag you set to indicate whether all text is selected. if true, then do TextView.setText(""). This will clear the text. Now set the flag to false again so that subsequent text changes will not cause the text to be cleared.

Anup Cowkur
  • 20,443
  • 6
  • 51
  • 84
0

This is working , all text will be selected and when user type something that will remove it.

             editText.setSelectAllOnFocus(true);

            editText.requestFocus();
            editText.postDelayed(new Runnable() {
                @Override
                public void run() {
                    InputMethodManager keyboard = (InputMethodManager) catalougeJobDetailFragment
                            .getActivity().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    keyboard.showSoftInput(commentEt, 0);
                }
            }, 20);