EditText & TextChangeListener

六眼飞鱼酱① 提交于 2019-12-04 20:13:16

I'm guessing you're using a TextWatcher because you want to make live searches. In that case you can't know when the user has finished input BUT you CAN limit the frequency of your searches.

Here's some sample code:

searchInput.addTextChangedListener(new TextWatcher()
{
    Handler handler = new Handler();
    Runnable delayedAction = null;

    @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( final Editable s)
    {
        //cancel the previous search if any
        if (delayedAction != null)
        {
            handler.removeCallbacks(delayedAction);
        }

        //define a new search
        delayedAction = new Runnable()
        {
            @Override
            public void run()
            {
                //start your search
                startSearch(s.toString());
            }
        };

        //delay this new search by one second
        handler.postDelayed(delayedAction, 1000);
    }
});

The only way to know if the input has ended is for the user to press enter or the search button or something. You can listen for that event with the following code:

searchInput.setOnEditorActionListener(new OnEditorActionListener()
{

    @Override
    public boolean onEditorAction( TextView v, int actionId, KeyEvent event)
    {
        switch (actionId)
        {
        case EditorInfo.IME_ACTION_SEARCH:
            //get the input string and start the search
            String searchString = v.getText().toString();
            startSearch(searchString);
            break;
        default:
            break;
        }
        return false;
    }
});

Just make sure to add android:imeOptions="actionSearch" to the EditText in the layout file.

How I usually do that is to use onFocusChange

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            // Do your thing here
        }
    }
});

This has the one drawback of the user having to move away from the edittext field though, so I'm not sure if it will fit in with what you are trying to do...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!