I have a Fragment with menu:
public class FragmentA extends Fragment {
public FragmentA() {
setHasOptionsMenu(true);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.activity_main_actions, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
I would like to change menu but it doesn't work and keep the old action menu
Fragment B is equals like above with different inflate XML menu.
public class FragmentB extends Fragment {
public FragmentB() {
setHasOptionsMenu(true);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.**action_ranking**, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
EDITED:
Can be useful to use different menu layout for different fragments and 1 menu layout for main activity and differents id
Use replace() to replace an existing fragment in a container with an instance of a new fragment class that you provide. Calling replace() is equivalent to calling remove() with a fragment in a container and adding a new fragment to that same container. transaction. commit();
You can use multiple instances of the same fragment class within the same activity, in multiple activities, or even as a child of another fragment.
When you click the show button to open a fragment, you can see the fragment menu items ordered before activity menu items. This is because of the menu item's android:orderInCategory attribute value. When you click the hide button to hide the fragment. The fragment menu items disappear from the action bar also.
Put setHasOptionsMenu(true)
in constructor and inflate fragment specific menu.
public class FragmentA extends Fragment {
public FragmentA() {
setHasOptionsMenu(true);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragmenta_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
menu in main activity
public class MainActivity extends Activity {
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With