问题
I am trying the ActionBarSherlock SearchView. unfortunately the
public boolean onKey(View arg0, int arg1, KeyEvent event)
is not fired. Do you know the reason? I see from this post SearchView imeOptions and onQueryTextSubmit support that a user solved the problem in another way. Maybe I should do the same?
Thanks
Here is my code:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//Used to put dark icons on light action bar
boolean isLight = SampleList.THEME == R.style.Theme_Sherlock_Light;
//Create the search view
final SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
searchView.setQueryHint("Search for countries…");
System.out.println("searchView.getQuery()"+searchView.getQuery());
searchView.setOnKeyListener(new OnKeyListener()
{
/**
* This listens for the user to press the enter button on
* the keyboard and then hides the virtual keyboard
*/
@Override
public boolean onKey(View arg0, int arg1, KeyEvent event) {
// If the event is a key-down event on the "enter" button
System.out.println("--->"+searchView.getQuery());
if ( (event.getAction() == KeyEvent.ACTION_DOWN ) &&
(arg1 == KeyEvent.KEYCODE_ENTER) )
{
InputMethodManager imm = (InputMethodManager) SearchViews.this.getSystemService(SearchViews.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
return true;
}
return false;
}
} );
menu.add("Search")
.setIcon(isLight ? R.drawable.ic_search_inverse : R.drawable.abs__ic_search)
.setActionView(searchView)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return true;
}
回答1:
Avoid doing anything like this. Use SearchView.OnQueryTextListener
final SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
searchView.setQueryHint("Search for countries..");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
@Override
public boolean onQueryTextSubmit(String query) {
if (query.length() != 0) {
System.out.println("--->" + query);
// handle search here
return true;
}
return false;
}
});
Always read the docs
来源:https://stackoverflow.com/questions/14772464/search-with-sherlock-actionbar-searchview-setonkeylistener