SearchView's OnCloseListener doesn't work

前端 未结 18 2472
有刺的猬
有刺的猬 2020-11-27 02:44

I\'m trying to add support for the SearchView in the Android 3.0+ ActionBar, but I can\'t get the OnCloseListener to work.

Here\'s my code:

18条回答
  •  温柔的废话
    2020-11-27 03:12

    Create the menu item with the app:showAsAction set to always.

    
    

    When creating the SearchView in the onCreateOptionsMenu method do something similar

    inflater.inflate(R.menu.menu_search, menu);
    final MenuItem item = menu.findItem(R.id.action_search);
    final SearchView search = (SearchView) item.getActionView();
    search.setQueryHint(getString(R.string.search_brand_item));
    search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
      @Override
      public boolean onQueryTextSubmit(String query) {
        // add your code
        return false;
      }
    
      @Override
      public boolean onQueryTextChange(String newText) {
        // add your code 
        return false;
      }
    });
    search.setOnCloseListener(new SearchView.OnCloseListener() {
      @Override
      public boolean onClose() {
        // add your code here
        return false;
      }
    });
    search.setIconifiedByDefault(true); // make sure to set this to true
    

    The search.setIconifiedByDefault(true) needs to be set to true to call the onClose() method on the SearchView.OnCloseListener() created above.

提交回复
热议问题