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;
}
});
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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With