AndroidEditText校验 只输入数字或特定字符

来源:互联网 发布:数据库管理第三版答案 编辑:程序博客网 时间:2024/05/21 20:55



EditText的layout设置大家都知道就不累赘了,这里主要说怎么设置输入限制。

EditText的属性里面已经封装好了相关的设置,上一篇文章里面也提到了,不熟悉的可以去查看上一篇EditText属性大全,这里着重讲输入限制的属性:

android:digits="1234567890.+-*/%\n()"
限制输入框中只能输入自己定义的这些字符串 如果输入其它将不予以显示
android:phoneNumber="true"
限制输入框中只能输入手机号码
android:password="true"
限制输入框中输入的任何内容将以"*"符号来显示
android:hint="默认文字"
输入内容前默认显示在输入框中的文字
android:textColorHint="#FF0000"
设置文字内容颜色
android:enabled="false"
设置输入框不能被编辑

如果还有一些特殊的限制,比如我做一个项目只能输入数字,且输入0之后再输入1,则只显示1,这就需要单独去进行设置了,也非常的简单。

给EditText添加一个监听事件,当检测到里面的内容变化以后,根据需求,修改相关的内容就可以了。

使用EditText的addTextChangedListener(TextWatcher watcher)方法对EditText实现监听,TextWatcher是一个接口类,所以必须实现TextWatcher里的抽象方法:

当EditText里面的内容有变化的时候,触发TextChangedListener事件,就会调用TextWatcher里面的抽象方法。

  1. public class MainActivity extends Activity { 
  2.     private EditText text; 
  3.     String str; 
  4.     @Override
  5.     public void onCreate(Bundle savedInstanceState) { 
  6.         super.onCreate(savedInstanceState); 
  7.         setContentView(R.layout.main); 
  8.          
  9.         text = (EditText)findViewById(R.id.text); 
  10.         text.addTextChangedListener(textWatcher); 
  11.     } 
  12.      
  13.     private TextWatcher textWatcher = new TextWatcher() { 
  14.          
  15.         @Override   
  16.         public void afterTextChanged(Editable s) {    
  17.             // TODO Auto-generated method stub   
  18.             Log.d("TAG","afterTextChanged--------------->");  
  19.         }  
  20.          
  21.         @Override
  22.         public void beforeTextChanged(CharSequence s, int start, int count, 
  23.                 int after) { 
  24.             // TODO Auto-generated method stub
  25.             Log.d("TAG","beforeTextChanged--------------->"); 
  26.         } 
  27.          @Override   
  28.         public void onTextChanged(CharSequence s, int start, int before,    
  29.                 int count) {    
  30.             Log.d("TAG","onTextChanged--------------->");   
  31.             str = text.getText().toString(); 
  32.             try 
  33.                 //if ((heighText.getText().toString())!=null) 
  34.                 Integer.parseInt(str); 
  35.                  
  36.             } catch (Exception e) { 
  37.                 // TODO: handle exception
  38.                 
  39.             } 
  40.                              
  41.         }                   
  42.     };
  43. }

 

该方法可以监听到Edittext的变化,我在onTextChanged里面监听s值得变化,然后做修改以后再setText到EditText里面,不过这时候经常会遇见光标跑到最前面的情况,很恶心,随意每次setText的时候都需要用ev.setSelection(str.length())去重新设置光标位置为str字符串的最后。


0 0