如何理解停止并开始像WhatsApp那样为EditText输入内容?

时间:2018-09-26 14:06:27

标签: android timer android-edittext textwatcher

我有edittext,并且我想了解停止并开始输入的内容。我听了textwatcher onTextChanged,并使用计时器输入内容。

但是,当edittext的文本不为空时,我无法正确理解实际的键入操作。

我想看:

  

我的edittext文本:

     

-ad--->键入...

     

-ads--->键入...

     

-ads---> 900毫秒后停止键入。 :::但不了解

TextWatcher textWatcher = new TextWatcher() {

        public void afterTextChanged(Editable s) {
        }

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

        public void onTextChanged(CharSequence s, int start, final int before, final int count) {

            if (count != 0 && count >= before) {
                typingTimer.startTyping();
                return;
            }

            typingTimer.stopTyping();

        }
    }; 

1 个答案:

答案 0 :(得分:0)

实际上您需要一个计时器。

TextWatcher textWatcher = new TextWatcher() {

    private Timer timer = new Timer();
    private final long TYPING_DELAY = 900; // milliseconds

    public void afterTextChanged(Editable s) {
    }

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

    public void onTextChanged(CharSequence s, int start, final int before, final int count) {

        // do what you want
        // show "is typing"

        timer.cancel();
        timer = new Timer();
        timer.schedule(
            new TimerTask() {
                @Override
                public void run() {
                    // here, you're not typing anymore
                }
            }, 
            TYPING_DELAY
        );

    }
};