Search code examples
androidactionbarsherlocksearchview

Handling hardware search to show searchview in ActionbarSherlock


I'm wondering how to do that : when the user press hardware search button, it's open a search view in the actionbar.

Basically I have an activity hosting fragments. One fragment add to the ActionbarSherlock a searchview, it's working fine:

@Override
public void onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu,
        MenuInflater inflater) {

    if(searchView==null)
        searchView = new SearchView(getSherlockActivity().getSupportActionBar().getThemedContext());

    searchView.setQueryHint(getString(R.string.search));
    searchView.setOnQueryTextListener(this);


        menu.add(Menu.NONE, R.string.search, Menu.NONE, R.string.search)
        .setIcon(R.drawable.abs__ic_search_api_holo_light)
        .setActionView(searchView)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);

    super.onCreateOptionsMenu(menu, inflater);
}

I think I can also catch the hardware key in the FragmentActivity with

@Override
public boolean onSearchRequested() {

    //DO SOMETHING

    return super.onSearchRequested();
}

But I do not see how to open the searchview when the hardware search button is pressed.

Any hint ?

Thanks :).


Solution

  • So, here how I managed to use the hardware search key to open the searchview in the sherlock actionbar :

    In my SherlockFragmentActivity :

    private Menu ABSMenu;
    
    @Override
    
    public boolean onCreateOptionsMenu(Menu menu) {
        ABSMenu = menu;
        return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onSearchRequested() {
    
        MenuItem mi = ABSMenu.findItem(R.string.search); // R.string.search is the id of the searchview
        if(mi!=null){
        if(mi.isActionViewExpanded())
         {
                mi.collapseActionView();
         }else 
         {
                mi.expandActionView();  
         }
        }
    
        return super.onSearchRequested();
    }