当前位置: 移动技术网 > IT编程>移动开发>Android > Android编程中EditText限制文字输入的方法

Android编程中EditText限制文字输入的方法

2019年07月24日  | 移动技术网IT编程  | 我要评论

铁道部刘志军,中条比纱也,珍幼阁最新网址

本文实例讲述了android编程中edittext限制文字输入的方法。分享给大家供大家参考,具体如下:

android的编辑框控件edittext在平常编程时会经常用到,有时候会对编辑框增加某些限制,如限制只能输入数字,最大输入的文字个数,不能输入一些非法字符等,这些需求有些可以使用android控件属性直接写在布局xml文件里,比如android:numeric="integer"(只允许输入数字);

对于一些需求,如非法字符限制(例如不允许输入#号,如果输入了#给出错误提示),做成动态判断更方便一些,而且容易扩展;

在android里使用textwatcher接口可以很方便的对edittext进行监听;textwatcher中有3个函数需要重载:

public void beforetextchanged(charsequence s, int start, int count, int after);
public void ontextchanged(charsequence s, int start, int before, int count);
public void aftertextchanged(editable s);

从函数名就可以知道其意思,每当敲击键盘编辑框的文字改变时,上面的三个函数都会执行,beforetextchanged可以给出变化之前的内容,ontextchanged和aftertextchanged给出追加上新的字符之后的文本;

所以对字符的限制判断可以在aftertextchanged函数中进行,如果检查到新追加的字符为认定的非法字符,则在这里将其delete掉,那么他就不会显示在编辑框里了:

private final textwatcher mtextwatcher = new textwatcher() {
 public void beforetextchanged(charsequence s, int start, int count, int after) {
 } 
 public void ontextchanged(charsequence s, int start, int before, int count) {
 } 
 public void aftertextchanged(editable s) {
  if (s.length() > 0) {
   int pos = s.length() - 1;
   char c = s.charat(pos);
   if (c == '#') {
   //这里限制在字串最后追加#
    s.delete(pos,pos+1);
    toast.maketext(myactivity.this, "error letter.",toast.length_short).show();
   }
  }
 }
};

注册监听:

edittext meditor = (edittext)findviewbyid(r.id.editor_input);
meditor.addtextchangedlistener(mtextwatcher);

希望本文所述对大家android程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网