简体   繁体   English

如何清除android textedit字段

[英]How to clear android textedit field

I am traing to clear textedit field when it is focused. 我正在训练着重于清除textedit字段。 I know about hint option, but I wanna clear textedit everytime when user actives it, also if is filled by user (now user have to clear field manualy everytime he wants change value). 我知道提示选项,但我想每次用户激活它时都清除textedit,也要由用户填充(现在,用户每次想要更改值时都必须手动清除字段)。 I load fragments in my app so there are a lot of edittext fields which I wanna clear on focus, so is there universal method to do this, or I have to do it to all fields severally? 我在应用程序中加载了片段,所以有很多我想重点关注的edittext字段,所以有通用的方法可以做到这一点,还是我必须分别对所有字段进行处理? Should I create another java file to this method or put inside onCreate? 我应该为此方法创建另一个Java文件还是将其放入onCreate中?

You need to add an onClickListener and set the textfield to an empty string when clicked. 您需要添加onClickListener并在单击时将文本字段设置为空字符串。 You need to add the listener for each textfield but you can reuse the same listener because the functionality is the same. 您需要为每个文本字段添加侦听器,但是您可以重复使用相同的侦听器,因为功能相同。 You can set the listener on onCreate , that's fine. 您可以在onCreate上设置侦听器,这很好。

You should you OnFocusChangeListener as is shown in code below: 您应该使用OnFocusChangeListener,如下面的代码所示:

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    ((EditText)v).setText("");
                }
            }
        });

Simply set an View.OnFocusChangeListener with the method setOnFocusChangeListener(View.OnFocusChangeListener l) . 只需使用setOnFocusChangeListener(View.OnFocusChangeListener l)方法设置一个View.OnFocusChangeListener

In the callback onFocusChange(View v, boolean hasFocus) you can do the following: 在回调onFocusChange(View v, boolean hasFocus)您可以执行以下操作:

if (hasFocus && v instanceof EditText) {
  ((EditText) v).setText("");
}

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

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