TextWatcher - 替换字符串的最后一个字符

时间:2014-06-13 01:59:51

标签: java textwatcher

每次“q”被写为我附加TextWatcher的edittext的最后一个字符,即“q”将替换为“a”。我用:

public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        if(s.length() > 0 && s.toString().charAt(s.length()-1) == 'q')
        {
            current_string = s.toString();
            current_string = current_string.substring(0, (current_string.length()-1));
            et.setText(current_string);
            }
        }

但是,当我测试代码时,当我输入“q”时没有任何反应。一些帮助?非常感谢

1 个答案:

答案 0 :(得分:0)

不要使用afterTextChanged这是危险的,因为它会被递归调用,你可能会陷入无限循环。

正如文件所说:

     It is legitimate to make further changes to s from this callback,
    but be careful not to get yourself into an infinite loop, because any 
   changes you make will cause this method to be called again recursively

改为使用onTextChanged

在你的问题中

您忘记将字符a添加到字符串

public void onTextChanged (CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub
    if(s.length() > 0 && s.toString().charAt(s.length()-1) == 'q')
    {
        current_string = s.toString();
        current_string = current_string.substring(0, (current_string.length()-1));
        et.setText(current_string + "a"); //add the a after q is deleted
        }
    }
}