有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android在不触发onTextChanged的情况下调用backspace

因此,我目前正在开发一个应用程序,它接受用户输入,启动一个退格来删除输入,然后添加一些其他文本。(因此,是的,我基本上是使用TextWatcher覆盖他们的输入)

没有问题:当我调用text.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));时,它会一次又一次地激发onTextChanged。现在有没有办法删除用户输入而不再次触发ContextChanged

谢谢


共 (3) 个答案

  1. # 1 楼答案

    不要从ContextChanged回调内部调度键事件。您可以为文本保留一个内部缓冲区,并在每个有趣的键事件上将整个TextView设置为该缓冲区

  2. # 2 楼答案

    您可能正在尝试使用TextWatcher进一步更改用户刚刚更改的文本。要做到这一点,最好的选择是使用afterTextChanged方法:

    public abstract void afterTextChanged (Editable s)
    

    This method is called to notify you that, somewhere within s, the text has been changed. 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.

    为了避免递归,您可以设置一个标志,指示您是更改文本的人,并在下一次调用中清除该标志。您还可以使用其他回调(beforeTextChangedonTextChanged)来收集有关更改的更多信息

    参考:http://developer.android.com/reference/android/text/TextWatcher.html

  3. # 3 楼答案

    我通过调用edittext.removeTextChangedListener(this);,然后分派密钥,然后再次调用edittext.addTextChangedListener(this);来修复它。这也是一种干净的方式吗?很高兴听到你的意见