[android] How to clear an EditText on click?

In Android how can I make an EditText clear when it's clicked?

E.g., if I have an EditText with some characters in, such as 'Enter Name', when the user clicks on it these characters disappear.

This question is related to android android-edittext

The answer is


((EditText) findViewById(R.id.User)).setText("");
((EditText) findViewById(R.id.Password)).setText("");

that is called hint in android use android:hint="Enter Name"


after onclick of any action do below step

((EditText) findViewById(R.id.yoursXmlId)).setText("");

or

write this in XML file

<EditText
---------- other stuffs ------ 
android:hint="Enter Name" /> 

its works fine for me. Hope to you all.


Are you looking for behavior similar to the x that shows up on the right side of text fields on an iphone that clears the text when tapped? It's called clearButtonMode there. Here is how to create that same functionality in an Android EditText view:

String value = "";//any text you are pre-filling in the EditText

final EditText et = new EditText(this);
et.setText(value);
final Drawable x = getResources().getDrawable(R.drawable.presence_offline);//your x image, this one from standard android images looks pretty good actually
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
et.setCompoundDrawables(null, null, value.equals("") ? null : x, null);
et.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (et.getCompoundDrawables()[2] == null) {
            return false;
        }
        if (event.getAction() != MotionEvent.ACTION_UP) {
            return false;
        }
        if (event.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {
            et.setText("");
            et.setCompoundDrawables(null, null, null, null);
        }
        return false;
    }
});
et.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        et.setCompoundDrawables(null, null, et.getText().toString().equals("") ? null : x, null);
    }

    @Override
    public void afterTextChanged(Editable arg0) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
});

Code for clearing up the text field when clicked

<EditText android:onClick="TextFieldClicked"/>

public void TextFieldClicked(View view){      
      if(view.getId()==R.id.editText1);
           text.setText("");    
}

Be careful when setting text with an onClick listener on the field you are setting the text. I was doing this and setting the text to an empty string. This was causing the pointer to come up to indicate where my cursor was, which will normally go away after a few seconds. When I did not wait for it to go away before leaving my page causing finish() to be called, it would cause a memory leak and crash my app. Took me a while to figure out what was causing the crash on this one..

Anyway, I would recommend using selectAll() in your on click listener rather than setText() if you can. This way, once the text is selected, the user can start typing and all of the previous text will be cleared.

pic of the suspect pointer: http://i.stack.imgur.com/juJnt.png


For me the easiest way... Create an public EditText, for Example "myEditText1"

public EditText myEditText1;

Then, connect it with the EditText which should get cleared

myEditText1 = (EditText) findViewById(R.id.numberfield);

After that, create an void which reacts to an click to the EditText an let it clear the Text inside it when its Focused, for Example

@OnClick(R.id.numberfield)
        void textGone(){
            if (myEditText1.isFocused()){
                myEditText1.setText("");

        }
    }

Hope i could help you, Have a nice Day everyone


If you want to have text in the edit text and remove it like you say, try:

    final EditText text_box = (EditText) findViewById(R.id.input_box);
    text_box.setOnFocusChangeListener(new OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View v, boolean hasFocus) 
        {
            if (hasFocus==true)
            {
                if (text_box.getText().toString().compareTo("Enter Text")==0)
                {
                    text_box.setText("");
                }
            }
        }
    });

@Harris's answer is great, I've implemented it as a separate subclass of EditText, which can make it easier to use if your code already adds TextChangedListeners.

Also, I've tweaked it so that, if you already use any Compound Drawables, it leaves them intact.

Code is here, for anyone who needs it:

package com.companyname.your

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

public class ClearableEditText extends EditText {

    public String defaultValue = "";
    final Drawable imgX = getResources().getDrawable(android.R.drawable.presence_offline ); // X image


    public ClearableEditText(Context context) {
        super(context);

        init();
    }

    public ClearableEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        init();
    }

    public ClearableEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

        init();
    }


    void init()  {

        // Set bounds of our X button
        imgX.setBounds(0, 0, imgX.getIntrinsicWidth(), imgX.getIntrinsicHeight());      

        // There may be initial text in the field, so we may need to display the button
        manageClearButton();

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                ClearableEditText et = ClearableEditText.this;

                // Is there an X showing?
                if (et.getCompoundDrawables()[2] == null) return false;
                // Only do this for up touches
                if (event.getAction() != MotionEvent.ACTION_UP) return false;
                // Is touch on our clear button?
                if (event.getX() > et.getWidth() - et.getPaddingRight() - imgX.getIntrinsicWidth()) {
                    et.setText("");
                    ClearableEditText.this.removeClearButton();
                }
                return false;
            }
        });

        this.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                ClearableEditText.this.manageClearButton();
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
        });
    }

    void manageClearButton() {
        if (this.getText().toString().equals("") )
            removeClearButton();
        else
            addClearButton();
    }
    void addClearButton() {
        this.setCompoundDrawables(this.getCompoundDrawables()[0], 
                this.getCompoundDrawables()[1],
                imgX,
                this.getCompoundDrawables()[3]);
    }
    void removeClearButton() {
        this.setCompoundDrawables(this.getCompoundDrawables()[0], 
                this.getCompoundDrawables()[1],
                null,
                this.getCompoundDrawables()[3]);
    }

}

I'm not sure if you are after this, but try this XML:

android:hint="Enter Name"

It displays that text when the input field is empty, selected or unselected.

Or if you want it to do exactly as you described, assign a onClickListener on the editText and set it empty with setText().


//To clear When Clear Button is Clicked

firstName = (EditText) findViewById(R.id.firstName);

    clear = (Button) findViewById(R.id.clearsearchSubmit);

    clear.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (v.getId() == R.id.clearsearchSubmit);
            firstName.setText("");
        }
    });

This will help to clear the wrong keywords that you have typed in so instead of pressing backspace again and again you can simply click the button to clear everything.It Worked For me. Hope It Helps