How to clear an EditText on click?

2019-01-10 07:53发布

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.

11条回答
干净又极端
2楼-- · 2019-01-10 08:39

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.

查看更多
狗以群分
3楼-- · 2019-01-10 08:39

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

查看更多
可以哭但决不认输i
4楼-- · 2019-01-10 08:40

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

查看更多
贼婆χ
5楼-- · 2019-01-10 08:41

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

查看更多
闹够了就滚
6楼-- · 2019-01-10 08:43
((EditText) findViewById(R.id.User)).setText("");
((EditText) findViewById(R.id.Password)).setText("");
查看更多
登录 后发表回答