Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate ActionBar Buttons on Rotation

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:

multiple actionbar menu items

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.

like image 403
CBA110 Avatar asked May 07 '15 19:05

CBA110


4 Answers

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);
}
like image 136
Cüneyt Avatar answered Oct 16 '22 08:10

Cüneyt


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.

like image 32
CBA110 Avatar answered Oct 16 '22 07:10

CBA110


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

like image 43
Blackbelt Avatar answered Oct 16 '22 09:10

Blackbelt


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();

like image 27
David Avatar answered Oct 16 '22 08:10

David