2017-08-25 109 views
1

我想隱藏一些菜單項時,搜索視圖擴展,所以這是我使用的代碼:的Android搜索查看不工作()

@Override 
public boolean onPrepareOptionsMenu(Menu menu) { 
    menu.findItem(R.id.action_refresh).setVisible(!isSearchOpen) 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    MenuItem searchMenuItem = menu.findItem(R.id.action_search) 
    SearchView searchView = searchMenuItem.getMenu(); 

    searchView.setOnQueryTextListener(this); 

    MenuItemCompat.setOnActionExpandListener(searchMenuItem, new MenuItemCompat.OnActionExpandListener() { 
     @Override 
     public boolean onMenuItemActionCollapse(MenuItem item) { 
      isSearchOpen = true; 
      invalidateOptionsMenu(); 

      return true; 
     } 

     @Override 
     public boolean onMenuItemActionExpand(MenuItem item) { 
      isSearchOpen = false; 
      invalidateOptionsMenu(); 
      return true; 
     } 
    }); 
} 

下面這段代碼如預期,除了一期工程:當我點擊搜索按鈕時,SearchView不會出現。我找不出什麼問題。我搜索了在堆棧溢出類似的問題,但我沒有找到固定的問題的任何答案,所以任何幫助將受到歡迎

回答

2

您可以試試這個方式隱藏和顯示其他選項菜單: -

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.search_menu, menu); 
    final MenuItem delMenu = menu.findItem(R.id.action_delete); 
    final MenuItem editMenu = menu.findItem(R.id.action_edit); 
    MenuItem searchMenu = menu.findItem(R.id.action_search); 
    SearchView searchView = (SearchView) searchMenu.getActionView(); 

    searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() { 
     @Override 
     public void onFocusChange(View view, boolean b) { 
      if(b) { 
       delMenu.setVisible(false); 
       editMenu.setVisible(false); 
      } 
     } 
    }); 
    searchView.setOnCloseListener(new SearchView.OnCloseListener() { 
     @Override 
     public boolean onClose() { 
      delMenu.setVisible(true); 
      editMenu.setVisible(true); 
      return false; 
     } 
    }); 
    return true; 
} 
+0

謝謝。這工作完美 –