I've tried to find an answer about this but with no luck. I have a fragment that has an a menu item called 'menu_roi_result_calc'. Every time there is a screen rotation, a new menu item is created. The code is shown below:
@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_roi_result_calc, menu);
return true;
}
However, after a couple of screen rotations, this is what I get:
I get the feeling this is due to the fact that the menu items are being recreated at every rotation, therefore adding a new item every time a rotation occurs. How do I get this to stop? How can I check if the item is there and prevent from recreating it again? Any code example would be greatly appreciated.
You must clear your menu object before adding items. I had the same problem and this was the best solution that I've found.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.menu_roi_result_calc, menu);
super.onCreateOptionsMenu(menu, inflater);
}
I found out what the issue was. I was not reusing the original tagged fragments. All I had to do was make sure to check savedInstanceState
and check if a tagged fragment had already been created... if so reuse the same fragment instead of creating a new one.
as workaround you could clear the menu, before inflating it again, calling clear
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.menu_roi_result_calc, menu);
return true;
}
it removes all entries from the menu, leaving it as it had just been created
When you rotate your application your activity is destroyed and a new one is created. If you are attaching your fragment to the activity where it is being created than it will have the old one attached and will attach a new one. To avoid this I would do something like below. This will remove all of the current fragments and host whatever yours is.
FragmentManager fm = new FragmentManager();
for(Fragment aFrag : fm.getFragments()) {
fm.beginTransaction().remove(aFrag).commit();
}
fragment = createFragment(new Fragment());
fm.beginTransaction().add(R.id.YouGetThePicture, fragment).commit();
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