如何使用 TextWatcher 更新相同的 EditText? [英] How to update the same EditText using TextWatcher?

查看:15
本文介绍了如何使用 TextWatcher 更新相同的 EditText?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Android 应用程序中,我需要实现一个 TextWatcher 接口来实现 onTextChanged.我遇到的问题是,我想用一些额外的字符串更新相同的 EditText.当我尝试这样做时,程序会终止.

In my Android application I need to implement a TextWatcher interface to implement onTextChanged. The problem I have is, I want to update the same EditText With some extra string. When I try to do this the program terminates.

 final EditText ET = (EditText) findViewById(R.id.editText1);
 ET.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            try
            {
                 ET.setText("***"+ s.toString());
                 ET.setSelection(s.length());
            }
            catch(Exception e)
            {
                Log.v("State", e.getMessage());
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {

        }

        @Override
        public void afterTextChanged(Editable s)
        {               
        }
    });

我的程序终止了,即使我尝试在我的代码中捕获异常,它仍然终止.有谁知道为什么会发生这种情况以及我如何做到这一点?谢谢.

My program terminates and even I try to catch the exception like in my code still it terminates. Does anyone have any idea why this happens and how I can achieve this? Thanks.

推荐答案

TextView 的内容在 onTextChanged 事件上不可编辑.

The content of the TextView is uneditable on the onTextChanged event.

相反,您需要处理 afterTextChanged 事件才能对文本进行更改.

Instead, you need to handle the afterTextChanged event to be able to make changes to the text.

更详尽的解释参见:Android TextWatcher.afterTextChanged vs TextWatcher.onTextChanged

注意:错误onTextChanged

显然,您正在通过不断更改 afterTextChanged 事件上的 text 导致无限循环.

Obvioulsy, you are causing an endless loop by continuously changing the text on afterTextChanged event.

来自 参考:

public abstract void afterTextChanged (Editable s)
调用此方法是为了通知您,在 s 中的某处,文本已被改变了.从此对 s 进行进一步更改是合法的回调,但注意不要让自己陷入无限循环,因为您所做的任何更改都会导致再次调用此方法递归地....

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆