Search code examples
androidsearchview

SearchView listen for IME actions


How can I listen for IME actions on a SearchView? Since it is not a subclass of EditText.

What I want to do is to handle when the user presses the "enter" key on the keyboard and there is no text entered.

The problem with there being no text is that OnQueryTextListener.onQueryTextSubmit() is only triggered if the user has entered text.


Solution

  • How about getting EditText of the searchview and using OnEditorAction?

    final SearchView searchView = (SearchView) findViewById(R.id.searchView);
    int searchViewPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
    EditText searchPlateEditText = (EditText) searchView.findViewById(searchViewPlateId);
    searchPlateEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                if(!TextUtils.isEmpty(v.getText().toString())){
                    //Text entered
                }
                else {
                    //no string
                }
            }
            return true;
        }
    
    });