如何阻止用户在 EditText 上输入特定字符

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

我需要阻止用户在数字 EditText 上从键盘输入 .(句点)字符,但我需要能够在同一个 [=12] 上使用它=] 通过 setText 方法。

我试过使用 InputFilter 但是当我调用 setText. 字符不显示。我也尝试在 xml 中设置 digits 参数,但 setText 也不起作用。

有办法吗?

这是我的 InputFilter 代码:

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

      }

  };

}

试试这个:

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

}

正在进入。你可以显示一条消息或其他东西 else.also 将此代码放在 onTextChanged 方法(文本观察器)下。

希望对您有所帮助。

你可以用你的 InputFilter 来完成它,但你需要在调用 setText() 方法时允许它一段时间。

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

EditText

中 xml 内的用户数字 属性
android:digits="0123456789"

所以现在 edittext 只允许从 0 到 9 的数字