简体   繁体   English

如何自动清除EditText中的文本?

[英]How can I automatically clear the text in EditText?

final TextView textView = (TextView) findViewById(R.id.textView);

final EditText editText = (EditText) findViewById(R.id.editText);

Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        String etString = editText.getText().toString();
        textView.setText(etString);
    }
});

I am new to coding and I don't know how to automatically clear the text in an EditText so the user doesn't have to do it themselves. 我是编码的新手,我不知道如何自动清除EditText中的文本,因此用户不必自己完成。 You can see in all "big" websites that when you enter text into a text box (for example: "What's your name?") you see "first name" in the text box and when you click on it, it disappears. 您可以在所有“大”网站上看到,当您在文本框中输入文本时(例如:“您叫什么名字?”),您会在文本框中看到“名字”,当您点击它时,它就会消失。 How can I make the text disappear automatically without the user having to delete it manually? 如果用户不必手动删除文本,如何使文本自动消失?

What you're referring to isn't actually text that's being set -- it's a hint (which is why it doesn't show after the EditText is focused or text has already been entered). 您所指的实际上并不是正在设置的文本 - 它是一个提示(这就是为什么在EditText被聚焦或文本已被输入之后它没有显示的原因)。 You can set these placeholder hints in your EditText XML, for example: 您可以在EditText XML中设置这些占位符提示,例如:

android:hint="First Name". 

If you're feeling really adventerous, you can also wrap your EditText in a TextInputLayout for a Material Design style floating hint. 如果您感觉非常冒昧, 您还可以将EditText包装在TextInputLayout中,以获得Material Design样式浮动提示。

If that helps, be sure to accept this answer. 如果这有帮助,请务必接受此答案。

You can do it grammatically by modifying your code to use the hint property: 您可以通过修改代码来使用提示属性来语法编写:

editText.setText("");
editText.setHint(<string>);

also you can change color by adding 你也可以通过添加来改变颜色

editText.setHintTextColor(<some color>);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM