Android SearchView.OnQueryTextListener OnQueryTextSubmit not fired on empty query string

后端 未结 13 886
盖世英雄少女心
盖世英雄少女心 2020-12-05 10:17

I am using Android 4.1.2. I have a SearchView widget on an ActionBar. Documentation on SearchView.OnQueryTextListener

13条回答
  •  长情又很酷
    2020-12-05 10:35

    This is a very dirty hack, however it works correctly as expected, enabling the submit action even when there is no text entered (or entered then edited) in the SearchView.

    It reflectively gains access to the inner TextView editor action listener, wraps it in a custom listener where it delegates the call to the handler, and finally sets it as the action listener of the inner TextView.

        Class klass = searchView.getClass();
        try {
            Field currentListenerField = klass.getDeclaredField("mOnEditorActionListener");
            currentListenerField.setAccessible(true);
            TextView.OnEditorActionListener previousListener = (TextView.OnEditorActionListener) currentListenerField.get(searchView);
            TextView.OnEditorActionListener newListener = new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (v.getText().length() == 0)
                        handleQuery("");
                    return previousListener.onEditorAction(v, actionId, event);
                }
            };
            Field innerTextViewField = klass.getDeclaredField("mSearchSrcTextView");
            innerTextViewField.setAccessible(true);
            SearchView.SearchAutoComplete innerTextView = (SearchView.SearchAutoComplete) innerTextViewField.get(searchView);
            innerTextView.setOnEditorActionListener(newListener);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    

提交回复
热议问题