android onCreateOptionsMenu called twice when restoring state

后端 未结 3 683
旧巷少年郎
旧巷少年郎 2020-12-18 01:30

Here\'s a simple android app I\'ve created to demonstrate my problem:

public class OptionMenuTest extends Activity {

    @Override
    protected void onCrea         


        
相关标签:
3条回答
  • 2020-12-18 02:17

    I have just cleared menu before inflating and works

     @Override
     public void   onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
          menu.clear();
          inflater.inflate(R.menu.call_menu, menu);
          super.onCreateOptionsMenu(menu, inflater);
    
     }
    
    0 讨论(0)
  • 2020-12-18 02:28

    I think I found the answer to this problem.

    Take a look a this:

    https://stackoverflow.com/a/7225296/48468

    The problem seems to be related to the fact that Android does not destroy the fragment when the activity is destroyed (when the device is rotated).

    Basically I added :

    setRetainInstance(true);
    

    to my fragment constructor and the problem go solved.

    Hope it helps!

    0 讨论(0)
  • 2020-12-18 02:31

    @Gerardo Contijoch answer is misleading, except for one fact:

    In your example both Activity and Fragment get destroyed upon rotation and created again. That is why onCreateOptionsMenu() is called twice. This is correct and expected behaviour.

    By setRetainInstance(true) you tell Android not to destroy the fragment. This may prove useful in case of UI-less fragment holding no Activity' context (useful for AsyncTasks coordination and some other service-like stuff).

    In other cases fragment this potentially leads to memory leak, which you are to avoid.

    0 讨论(0)
提交回复
热议问题