在onTextChanged中取消postDelayed

时间:2016-12-09 08:56:22

标签: java android

我希望每次更新EditText的值时将Web服务调用3秒,但如果您在3秒之前更新EditText的值,请删除所有延迟回调并等待3用于Web服务调用的秒。请查看我的cod并让我知道执行此任务的正确方法

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

    if (s.length() > 2) {

        final Handler handler = new Handler();
        handler.removeCallbacksAndMessages(null);
        handler.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {

                        // Soap call

                    }
                },
                3000);
    }
}

2 个答案:

答案 0 :(得分:0)

试试这个。

long lastTime = System.currentTimeMillis();
final Handler handler;
public void onTextChanged(final CharSequence s, int start, int before, int count) {
    if(s.length() > 2) {
        if (System.currentTimeMillis() - lastTime > 3000) {
            startWork();
        }
        lastTime = System.currentTimeMillis();
    }
}

public void startWork() {
    if (null == handler) {
       handler = new Handler();
    }
    handler.removeCallbacksAndMessages(null);
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            //Soap call
        }
    }, 3000);
}

答案 1 :(得分:0)

试用此代码

它将解决您的问题。

final Handler handler = new Handler();
    final Runnable runnable = new Runnable() {
        @Override
        public void run() {

            //Soap Call;
        }
    };

    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {


        }

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

             handler.removeCallbacks(runnable);
        }

        @Override
        public void afterTextChanged(Editable s) {

            handler.postDelayed(runnable, 3000);

        }
    });