简体   繁体   中英

How to clear android textedit field

I am traing to clear textedit field when it is focused. 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). 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? Should I create another java file to this method or put inside onCreate?

You need to add an onClickListener and set the textfield to an empty string when clicked. 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.

You should you OnFocusChangeListener as is shown in code below:

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

In the callback onFocusChange(View v, boolean hasFocus) you can do the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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