简体   繁体   中英

Remove character from string while typing string

I have EditText widget and I want to remove character "-" right in that moment if someone types it in EditText.

You can try with an InputFilter :

editText.filters = arrayOf(InputFilter { 
    src, _, _, _, _, _ -> src.replace("-".toRegex(), "") 
})

or, in Java:

editText.setFilters(new InputFilter[] {
    (source, start, end, dest, dstart, dend) -> { 
        source.toString().replaceAll("-", "")
    }
);

I assume you are implementing this feature in Android. So, if it is the android, in your edit text you implement TextWatcher which watches text changes. Whenever text changes or current edit text value changes you need all of these callback methods called time sequentially. When afterTextChanged() when text change is fully effective you may remove - character as give below. Given code is in Java.

EditText.addTextChangedListener(new TextWatcher() {

       @Override
       public void afterTextChanged(Editable s) { s.replace("-".toRegex(),"")}

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

       @Override    
       public void onTextChanged(CharSequence s, int start,
         int before, int count) {

       }
      });

Or you may use the inputFilter in xml file or programmatically to set rules what characters your edit text should get and what character it must ignore.

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