Duplicate ActionBar buttons during rotation

I tried to find an answer about this, but no luck. I have a snippet that has a menu item called "menu_roi_result_calc". Each time you rotate the screen, 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 few turns of the screen, this is what I get:

multiple actionbar menu items

It seems to me that this is due to the fact that menu items are recreated with each rotation, so every time a rotation occurs, a new element is added. How can I stop this? How can I check if there is an element and not recreate it again? Any code sample is greatly appreciated.

+6
source share
4 answers

I found out what the problem is. I did not reuse the original tagged snippets. All I had to do was check savedInstanceState and check if the fragment tag was already created ... if reusing the same fragment instead of creating a new one.

+5
source

Before adding items, you must clear the menu object. I had the same problem and it was the best solution I found.

 @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { menu.clear(); inflater.inflate(R.menu.menu_roi_result_calc, menu); super.onCreateOptionsMenu(menu, inflater); } 
+4
source

as a workaround, you can clear the menu before inflating it again by calling clear

 @Override public boolean onCreateOptionsMenu(Menu menu) { menu.clear(); getMenuInflater().inflate(R.menu.menu_roi_result_calc, menu); return true; } 

it deletes all entries from the menu, leaving it as just created

+1
source

When you turn the application, your activity is destroyed and a new one is created. If you attach your fragment to the activity in which it is created, it will be attached to the old one and add a new one. To avoid this, I would do something like below. This will remove all current fragments and place all your data. 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();

0
source

Source: https://habr.com/ru/post/986774/


All Articles