Search code examples
javaandroidandroid-actionbaractionbarsherlock

Mutiple menu icons generated onResume of fragments


hey guys this a function in my fragment view to dynamically add a item in my action bar.

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Inflate the menu; this adds items to the action bar if it is present.
         super.onCreateOptionsMenu(menu, inflater);
         fav = menu.add(1,1,1,"add");
         fav.setIcon(R.drawable.add_label);
         fav.setShowAsAction(2);
    }

my problem is when the device is locked and resumed the item duplicates it self in the action bar. any insight to solve the problem is appreciated. thanks


Solution

  • Try use

    fav = menu.findItem(R.id.fav);
    if(fav == null) {
        fav = menu.add(1,1,1,"add");
    }
    

    where R.id.fav is the id of your item in menu xml layout.