如何检测用户是否停止在 EditText android 中输入

时间:2023-03-25
本文介绍了如何检测用户是否停止在 EditText android 中输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我的布局中有一个 EditText 字段.当用户停止在该编辑文本字段中输入时,我想执行一项操作.我已经实现了 TextWatcher 并使用了它的功能

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

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


@Override
public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { } 

@Override
    public void afterTextChanged(Editable editable) {

    }

函数 onTextChangedafterTextChanged 在输入任何字符后被调用,但我想在用户完成输入该编辑文本字段后执行操作,就像 facebook在它的签入"页面上.

The function onTextChanged and afterTextChanged get called just after typing any character, but I want to perform action after the user has finished typing in that edittext field, just like facebook does on it's "Check In" page.

我该如何实现?

推荐答案

这就是我的工作方式!

long delay = 1000; // 1 seconds after user stops typing
long last_text_edit = 0;
Handler handler = new Handler();

private Runnable input_finish_checker = new Runnable() {
    public void run() {
        if (System.currentTimeMillis() > (last_text_edit + delay - 500)) {
            // TODO: do what you need here
            // ............
            // ............
            DoStuff();
        }
    }
};

EditText editText = (EditText) findViewById(R.id.editTextStopId);
editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged (CharSequence s,int start, int count,
    int after){
    }
    @Override
    public void onTextChanged ( final CharSequence s, int start, int before,
    int count){
        //You need to remove this to run only once
        handler.removeCallbacks(input_finish_checker);

    }
    @Override
    public void afterTextChanged ( final Editable s){
        //avoid triggering event when text is empty
        if (s.length() > 0) {
            last_text_edit = System.currentTimeMillis();
            handler.postDelayed(input_finish_checker, delay);
        } else {

        }
    }
}

);

这篇关于如何检测用户是否停止在 EditText android 中输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:用户打字时如何避免 EditText 上的多个触发器? 下一篇:为什么自定义复合视图中的 EditText 会重复使用在另一个复合视图实例中输入的文本?

相关文章