javaandroidandroid-edittextinput-filter

How to block user from inputing a specific character on a EditText


I need to block the user from inputing the . (period) character from the keyboard on a number EditText, but I need to be able to use it on the same EditText via the setText method.

I've tried using InputFilter but when I call setText the . character don't show. I've also tried setting the digits parameter in the xml but the setText doesn't work either.

Is there a way to do this?

Here's my InputFilter code:

public static InputFilter blockPeriod(){

    return new InputFilter() {
      @Override
      public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {

          for (int j = i; j <i1 ; j++) {

              char c = charSequence.charAt(j);
              if (!allowed(c)){

                  return "";

              }

          }

          return null;
      }

      private boolean allowed(char c){

          return c != '.';

      }

  };

}

Solution

  • You can do it with your InputFilter, but you need to allow it for a while when you calling setText() method.

    private static class AllowableInputFilter implements InputFilter {
        private boolean mAllowDot;
    
        public void setAllowDot(boolean toAllow) {
          mAllowDot = toAllow;
        }
    
        ....
    
    
        private boolean allowed(char c){
          return mAllowDot || c != '.';
        }
    }
    
    public void forceText(String text) {
      mInputFilter.setAllowDot(true);
      mEditText.setText(text);
      mInputFilter.setAllowDot(false);
    }
    
    mInputFilter = new AllowableInputFilter();
    mInputFilter.setAllowDot(false);
    
    mEditText.setFilters(new InputFilter[] {mInputFilter});
    
    forceText("Okaaayy....");