5

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?

Xtreme Biker
  • 28,480
  • 12
  • 120
  • 195

2 Answers2

4

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:

Community
  • 1
  • 1
Xtreme Biker
  • 28,480
  • 12
  • 120
  • 195
-1

In layout set your input method options to search.

<EditText
android:imeOptions="actionSearch" 
android:inputType="text" />

In your java class add editor action listener.

  viewHolder.mTextSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
        performSearch();
        return true;
    }
    return false;
}

});

Adnan Bin Mustafa
  • 1,219
  • 10
  • 20