How to detect if users stop typing in EditText android

前端 未结 7 1351
长情又很酷
长情又很酷 2020-12-24 14:31

I have an EditText field in my layout. I want to perform an action when the user stops typing in that edittext field. I have implemented TextWatcher and use its functions

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-24 15:19

    It is a little different kind of approach. But you can do something like this

    I am assuming that after a user started typing in the edittext, and he didn't typed for a particular time period than it can be considered that he stopped typing.

    editText.addTextChangedListener(new TextWatcher() {
    
            boolean isTyping = false;
    
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
    
            private Timer timer = new Timer();
            private final long DELAY = 5000; // milliseconds
    
            @Override
            public void afterTextChanged(final Editable s) {
                Log.d("", "");
                if(!isTyping) {
                    Log.d(TAG, "started typing");
                    // Send notification for start typing event
                    isTyping = true;
                }
                timer.cancel();
                timer = new Timer();
                timer.schedule(
                        new TimerTask() {
                            @Override
                            public void run() {
                                isTyping = false;
                                Log.d(TAG, "stopped typing");
                                //send notification for stopped typing event
                            }
                        },
                        DELAY
                );
            }
        });
    

    Basically what you are doing here is, that whenever a user starts typing, if there is a time gap of 5000 milliseconds in changing the text inside the edittext, you consider as the user has stopped typing. Of course you can change the time to whatever you want

提交回复
热议问题