EditText上 - 允许范围内,只知道特定的字符 [英] EditText - allow only specific characters known from context

查看:155
本文介绍了EditText上 - 允许范围内,只知道特定的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序,我有的EditText 。我希望用户能够插入只有数字和由我指定的两个字符。我知道存在安卓位数=...而是因为我这两个字从上下文中得到我不能使用此。现在我写的KeyListener:

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.

有谁知道如何正确地写这个的KeyListener?先谢谢了。

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

推荐答案

这是做这样的工作的正确方法

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}); 

这篇关于EditText上 - 允许范围内,只知道特定的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆