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

87 views Asked by At

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 != '.';

      }

  };

}
3

There are 3 answers

0
Orest Savchak On BEST ANSWER

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....");
0
Apoorv Mehrotra On

try this out :

 if (textedit.getText().toString().startsWith(".")){
//Do something about it

}

now entering . you can show a message or something else.also put this code under onTextChanged method(text watcher).

Hope it helps you out.

0
Anil Kanani On

user digits property inside xml in EditText

android:digits="0123456789"

so now edittext only allow digit from 0 to 9