Search code examples
androidandroid-3.0-honeycombandroid-actionbar

KeyListener on SearchView in Honeycomb ActionBar does not work


Here is my code. The onKey() method is never called when typing into the search box. Am I doing something wrong in setting up the listener? I have a breakpoint in the onKey() method, which is how I know it doesn't fire.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.locations_map_menu, menu);

    ActionBar ab = getActionBar();
    ab.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar));
    ab.setDisplayShowTitleEnabled(false);

    SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
    searchView.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            return true; // This code never fires
        }
    });
    return true;
}

Solution

  • Add an OnQueryTextListener, see my answer here

    final SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() { 
        @Override 
        public boolean onQueryTextChange(String newText) { 
            // Do something 
            return true; 
        } 
    
        @Override 
        public boolean onQueryTextSubmit(String query) { 
            // Do something 
            return true; 
        } 
    }; 
    
    searchView.setOnQueryTextListener(queryTextListener);