Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling physical keyboard's Enter key in SearchView

I've implemented a SearchView in my application which is working properly when I hit the search button while I'm using the soft keyboard (using the QueryTextListener):

viewHolder.mTextSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        new SearchForEquipmentTask(false, viewHolder.mTextSearch.getQuery().toString()).execute();
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        //Log.d(TAG, "Query: " + newText);
        return false;
    }
});

enter image description here

Now I'm planning to use a physical keyboard for my users to be able to work with the app, but I can't figure out how to fire the search event from the physical keyboard (onQueryTextChange is not getting invoked with that key). Same thing happens when I'm running the emulator in Android Studio. I've tried:

viewHolder.mTextSearch.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        Log.d(TAG, "Query: " + keyEvent);
        return false;
    }
});

But the SearchView seems to ignore the listener for any key... It seems that QueryTextListener is the only way to handle searches, but how to deal with special characters? Should I switch it to EditText which is more flexible?

Any idea?

like image 581
Xtreme Biker Avatar asked Oct 18 '22 14:10

Xtreme Biker


1 Answers

That's how I've handled it:

//Grab de EditText from the SearchView
EditText editText = (EditText) viewHolder.mTextSearch
    .findViewById(android.support.v7.appcompat.R.id.search_src_text);
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int keyAction, KeyEvent keyEvent) {
        if (
            //Soft keyboard search
                keyAction == EditorInfo.IME_ACTION_SEARCH ||
                        //Physical keyboard enter key
                        (keyEvent != null && KeyEvent.KEYCODE_ENTER == keyEvent.getKeyCode()
                                && keyEvent.getAction() == KeyEvent.ACTION_DOWN)) {
            new SearchForEquipmentTask(false, viewHolder.mTextSearch
                .getQuery().toString()).execute();
            return true;
        }
        return false;
    }
});

Thanks for your help!

See also:

  • Grab the EditText element from a SearchView
  • Android: how to make keyboard enter button say "Search" and handle its click?
like image 57
Xtreme Biker Avatar answered Oct 22 '22 18:10

Xtreme Biker