How to monitor edittext input completion

Reprinted in: http://blog.csdn.net/harryweasley/article/details/50395209

If you want to do such a function, you can search by entering some characters in the edit box, and then display the search results after the input is completed. During the input process, you don’t want to keep notifying the server to obtain the data.

Assuming such a scenario, you want to search for the game "1024", then you definitely don't want to communicate with the server once when you enter 1, if this puts too much pressure on the server, you definitely hope that when you finish losing After 1024, interact with the server and display the data.

This blog is to monitor the editText input, and then interact with the server to obtain data, which greatly reduces the pressure on the server.

The following is the specific implementation code:

private Handler handler = new Handler();

/**
     * 延迟线程,看是否还有下一个字符输入
     */
    private Runnable delayRun = new Runnable() {

        @Override
        public void run() {
        //在这里调用服务器的接口,获取数据
                getSearchResult(editString, "all", 1, "true");
        }
    };

search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
            }

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

            @Override
            public void afterTextChanged(Editable s) {

                if(delayRun!=null){
                //每次editText有变化的时候,则移除上次发出的延迟线程
                    handler.removeCallbacks(delayRun);
                }
                editString = s.toString();

                //延迟800ms,如果不再输入字符,则执行该线程的run方法
                handler.postDelayed(delayRun, 800);


            }
        });


Above, two technologies are mainly used
1.

handler.postDelayed(delayRun, 800) Delay 800ms execution thread

2.
handler.removeCallbacks(delayRun); Remove the thread to be executed in the current MessageQueue

Guess you like

Origin blog.csdn.net/weixin_45612718/article/details/128100474