gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:47:44 24 4
gpt4 key购买 nike

每次将“q”写入我附加 TextWatcher 的编辑文本的最后一个字符时,“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”时什么也没有发生。一些帮助?非常感谢

最佳答案

不要使用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
}
}
}

关于java - TextWatcher - 替换字符串的最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24196600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com