android 监听edittext addTextChangedListene

来源:互联网 发布:俄罗斯高加索知乎 编辑:程序博客网 时间:2024/05/17 08:13

    android中提供了对edittext控件的监听方法addTextChangedListene,下面记录一下在使用时容易犯的小错误。

    先来看一下addTextChangedListene的内容:

    edittext = (EditText) findViewById(R.id.edittext);
        edittext.addTextChangedListener(new TextWatcher() {
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                
            }
            
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub
                
            }
            
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                
            }
        });

     addTextChangedListener监听事件里面的三个方法顾名思义,按以上分别表示的是:内容改变时监听,内容改变前监听,内容改变后监听。当你在edittext中输入内容时,以上方法的触发顺序是:beforeTextChanged,onTextChanged,afterTextChanged,大多数情况下,我们都把监听事件写在onTextChanged中,用来实时监听edittext内容的变化。在onTextChanged方法中,有四个参数CharSequence s, int start, int before, int count,我们经常会用到CharSequence s,和 int count这两个参数。 int count是指这一次你输入了几个字符,注意,这里不是edittext中所有字符的个数总和,而是单单指你在这一次输入中添加了几个字符我们再来看看CharSequence s,这个参数返回的是整个edittext中的字符,所以如果我们想对edittext的内容进行判断或者约束就可以利用CharSequence s这个参数,比如:

     if(s.toString().equals("某某")){

   

    }

     但是,大家在使用时会发现程序有时候会报错,原因就是上面的语句没有考虑到当CharSequence s为null的情况,也就是说当你在edittext中输入内容后又删除了内容时,edittext中的内容变为了空,而当字符串为null时是不可以使用equals进行比较的,否则程序就会报错,所以大家在对CharSequence s进行比较时要先判断其是否为null。

0 0