Home » Android » java – EditText clear text on first focus – Android

java – EditText clear text on first focus – Android

Posted by: admin June 15, 2020 Leave a comment


I have few EditText objects with text inside. I want that on the first time an EditText is getting focus to delete the text in it, but only on the first time.

How can i do it?

Here’s an example:
I have an EditText called SomeThing with the text “someText” in it.
when the user touches SomeThing for the first time i want the “someText” to be deleted.
so let’s say the text was deleted and now the user typed in his own text, this time “someOtherText”, and the EditText lost focus for some other EditText. This time when the user will tap SomeThing, “someOtherText” won’t get deleted because that’s the second time it get’s focus.

How to&Answers:

Matan, I am not sure if this is what you are looking at, but I think you want to display a ‘hint’ for your Edit Text


 android:hint="Please enter your name here">

For an example check this http://www.giantflyingsaucer.com/blog/wp-content/uploads/2010/08/android-edittext-example-3a.jpg


If you are looking for a way to add placeholder for the EditText, just add android:hint = 'some text' to the corresponding XML file or call the setHint('some text') method on the EditText.

Otherwise, you can use the OnFocusChangeListener() to respond to the get focused event. To check if it is the first time for the EditText to get focused, use another Boolean variable (e.g., isFirstTimeGetFocused) and initialized it to true in onCreate() method. After the EditText gets focused, set isFirstTimeGetFocused to false;

editText.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
    if(hasFocus && isFirstTimeGetFocused){
        isFirstTimeGetFocused = false;