2016-07-11 46 views
2

我想爲我的主要活動提供一個菜單,併爲主要活動中包含的一個片段提供一個菜單。當該片段可見時,主活動菜單應該被移除並且片段菜單被充氣。我試圖做到這一點卻是這樣的結果:如何在活動中使用片段中的不同菜單?

主要活動菜單片段本身:在顯示片段

enter image description here

主要業務菜單片斷:

enter image description here

很顯然,我不會替換主要活動中的菜單,儘管已經創建並充實了一個片段菜單,但我正在添加它。

這裏是在活動負責這個代碼:

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    // Depending on which fragment is used display different actions. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

這裏是在片段負責此代碼:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
setHasOptionsMenu(true); 
} 

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

這裏是friend_menu.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:app="http://schemas.android.com/apk/res-auto"> 

    <item 
    android:icon="@drawable/ic_person_add_black_24dp" 
    android:id="@+id/nav_person_add" 
    android:title="Add people" 
    app:showAsAction="ifRoom" /> 

</menu> 

如何獲得我想要的菜單(沒有搜索動作和add_friend動作)?我意識到,從活動中管理這個可能會更簡單,只有當活動中的評論顯示片段時,纔會給特定的片段菜單充氣。// Depending on which fragment is used display different actions.

回答

1

您可以嘗試clear()菜單,如果您想保留這樣的結構。

在你Fragment

@Override 
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
    menu.clear(); // Remove all existing items from the menu, leaving it empty as if it had just been created. 
    inflater.inflate(R.menu.friend_menu, menu); 
}