2016-03-04 34 views
-1

只要我建立一個新的項目,我用下面的代碼設置了一個搜索選項的菜單。爲什麼我的菜單不斷消失?

@Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     MenuInflater menuInflater = getMenuInflater(); 
     menuInflater.inflate(R.menu.menu_main, menu); 


     mSearchMenuItem = menu.findItem(R.id.action_search); 
     mSearchView = (SearchView) MenuItemCompat.getActionView(mSearchMenuItem); 
     mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { 
      @Override 
      public boolean onQueryTextSubmit(String query) { 
       return false; 
      } 

      @Override 
      public boolean onQueryTextChange(String newText) { 
       return false; 
      } 
     }); 
     return true; 
    } 

當我運行並測試它似乎只要我更多的文件添加到項目中進行菜單操作好嗎但和動作條永遠消失?我不改變我的項目的樣式,我希望我的操作欄/搜索選項菜單留在那裏。

只要應用程序啓動即時通訊啓動一個對話框轉到webview,但在後臺我想要這個搜索選項,我希望用戶能夠搜索對話框消失時。

+0

請諒解se創建一個[MCVE](http://stackoverflow.com/help/mcve)。 – tachyonflux

回答

0

您的菜單的XML必須是這樣的

<item 
    android:id="@+id/action_search" 
    android:icon="@android:drawable/ic_menu_search" 
    android:title="@string/action_search" 
    app:actionViewClass="android.support.v7.widget.SearchView" 
    app:showAsAction="always|collapseActionView" /> 

YourActivity.class

@Override 
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
    inflater.inflate(R.menu.menu_main, menu); 

    final MenuItem item = menu.findItem(R.id.action_search); 
    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item); 
    //implements SearchView.OnQueryTextListener before this method 
    searchView.setOnQueryTextListener(this); 

    MenuItemCompat.setOnActionExpandListener(item, 
      new MenuItemCompat.OnActionExpandListener() { 
       @Override 
       public boolean onMenuItemActionCollapse(MenuItem item) { 
        // Do something when collapsed 
        return true; // Return true to collapse action view 
       } 

       @Override 
       public boolean onMenuItemActionExpand(MenuItem item) { 
        // Do something when expanded 
        return true; // Return true to expand action view 
       } 
      }); 
} 

,如果你寫這樣它會很容易(=