TextWatcher方法被多次调用

时间:2018-09-18 09:36:57

标签: android recycler-adapter textwatcher android-textwatcher addtextchangedlistener

我在Adapter中有一个编辑文本,已将addTextChangedListener附加到它上,并且它的所有方法多次调用, 我的输出就像,如果我想把Home输出像H Ho Hom Home

1 个答案:

答案 0 :(得分:0)

编辑:在用户键入内容时使用计时器取消处理

您可以尝试添加计时器以处理文本,并在用户键入时取消此处理。

private Timer timer;

myButton.addTextChangedListener(new TextWatcher() {  
    @Override
    public void afterTextChanged(Editable arg0) {
        // user typed: start the timer
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // do your actual work here
            }
        }, 600); // 600ms delay before the timer executes the „run“ method from TimerTask
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // nothing to do here
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // user is typing: reset already started timer (if existing)
        if (timer != null) {
            timer.cancel();
        }
    }
});

希望有帮助!