EditText - allow only specific characters known fr

2019-08-03 06:09发布

问题:

In my app i have EditText. I want user to be able to insert only digits and two characters specified by me. I know there exists android:digits="..." but I can't use this because i get these two characters from context. For now i wrote KeyListener:

public class CurrencyKeyListener implements KeyListener {

  @Override
  public void clearMetaKeyState(View view, Editable content, int states) {
    // TODO Auto-generated method stub

  }

  @Override
  public int getInputType() {
    return InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL;
  }

  @Override
  public boolean onKeyDown(View view, Editable text, int keyCode, KeyEvent event) {
    return false;
  }

  @Override
  public boolean onKeyOther(View view, Editable text, KeyEvent event) {
    // TODO Auto-generated method stub
    return false;
  }

  @Override
  public boolean onKeyUp(View view, Editable text, int keyCode, KeyEvent event) {
    CharFormatter charFormatter = new CharFormatter(view.getContext());
    char pressedKey = (char) event.getUnicodeChar();
    if (Character.isDigit(pressedKey) || pressedKey == currencyFormatter.getDecimalSeparator()
        || pressedKey == currencyFormatter.getGroupingSeparator()) {
      return false;
    }
    return true;
  }

}

but of course it doesn't work and i have no idea how to fix that. This listener blocks many important characters like clear button and allows to input many characters i don't want to allow. Then in some random moments it blocks my whole keyboard.

Does anyone know how to write this KeyListener properly? Thanks in advance.

回答1:

This is the proper way to do such task

InputFilter filter = new InputFilter() { 
        public CharSequence filter(CharSequence source, int start, int end, 
Spanned dest, int dstart, int dend) { 
                for (int i = start; i < end; i++) { 
                        // Your condition here 
                        if (!Character.isLetterOrDigit(source.charAt(i))) { 
                                return ""; 
                        } 
                } 
                return null; 
        } 
}; 

edit.setFilters(new InputFilter[]{filter}); 


回答2:

see my answer here how to create custom InputFilter InputFilter on EditText cause repeating text, of course you have to modify a bit filtering condition