EditText clear text on first focus - Android

11,918

Solution 1

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

Example

<EditText
.
.
 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

Solution 2

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() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
    if(hasFocus && isFirstTimeGetFocused){
        editText.setText("");
        isFirstTimeGetFocused = false;
    }
});
Share:
11,918
Matan Kadosh
Author by

Matan Kadosh

Updated on June 26, 2022

Comments

  • Matan Kadosh
    Matan Kadosh almost 2 years

    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.

  • Andrea Leganza
    Andrea Leganza over 6 years
    Note: if the field is the first on your hierarchy you should set focusable and focusableintouchmode in root viewgroup to avoid being already focused on activity start.