开发者

how to restrict capital letter typing in android programmatically?

I w开发者_开发技巧ant to restrict capital letter typing through keyboard on my form.

any one guide me how to achieve this?


In source code:

InputFilter smallFilter = new InputFilter() {

  @Override
  public CharSequence filter(CharSequence source, int start, int end,
      Spanned dest, int dstart, int dend) {
    for (int i = start; i < end; i++) {
      if (Character.isUpperCase(source.charAt(i))) {
        char[] v = new char[end - start];
        TextUtils.getChars(source, start, end, v, 0);
        String s = new String(v).toLowerCase();

        if (source instanceof Spanned) {
          SpannableString sp = new SpannableString(s);
          TextUtils
              .copySpansFrom((Spanned) source, start, end, null, sp, 0);
          return sp;
        } else {
          return s;
        }
      }
    }
    return null;
  }
};

EditText vText = ...;
vText.setFilters(new InputFilter[]{smallFilter});

It is based on Android source of: InputFilter.AllCaps. Tested and works.


First, what's your goal? Why do you want to restrict capital letters? Can't you take care of them on the validation of user input and use toLowerCase()

If you do need to restrict capital letters, the only way I can think of is overriding onTextChanged(CharSequence text, int start, int before, int after) and trying to do whatever you want inside it. I haven't tested it, but it might work.

Update: radek mentioned InputFilter. That solutions seems cleaner than mine, but I've never used them.

InputFilters can be attached to Editables to constrain the changes that can be made to them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜