title: ViewPager Tab Navigation Fragment ActionBar Menu Issue
body: <p>I'm facing an issue with my app.</p>
  
  <p>I set up a <code>ViewPager</code> with three actionbar tabs.
  When the App is openend, the next tab is preloaded (or something)</p>
  
  <p>Example: I swipe from tab A to tab B. When tab B is displayed, tab C is created in the background.</p>
  
  <p>Tab C itself has a special ActionBar Menu item, which should be displayed only in tab 3. Because it gets preloaded, this symbol is displayed in both tab B and tab C.</p>
  
  <p>If I call <code>setHasOptionsMenu(false)</code> in tab B, tab C overwrites it with its <code>setHasOptionsMenu(true)</code> (I still want to display the special item)</p>
  
  <p>I googled and stackoverflowed a few hours to find a workaround, but unfortunately, I got no results.</p>
  
  <p>Is there any way to fix this and can somebody explain this behavior to me?</p>
  
  <p><strong>EDIT: Some Code.</strong></p>
  
  <p><em>MainActivity</em></p>
  
  <pre><code>@Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main_pager);
  
      mPagerAdapter =new MyPagerAdapter(getFragmentManager());
      mViewPager = (ViewPager) findViewById(R.id.pager);
      mViewPager.setAdapter(mPagerAdapter);
  
      mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
  
          @Override
          public void onPageSelected(int position) {
              // on changing the page
              // make respected tab selected
              //invalidateOptionsMenu();
              actionBar.setSelectedNavigationItem(position);
          }
  
          @Override
          public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
  
          }
  
          @Override
          public void onPageScrollStateChanged(int arg0) {
          }
      });
  
  
      actionBar = getActionBar();
      actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
  
      tabListener = new FilmKisteTabListener();
      for (int tab_name : tabs) {
          actionBar.addTab(actionBar.newTab().setText(tab_name)
                  .setTabListener(tabListener));
      }   
  }
  
  protected class FilmKisteTabListener implements ActionBar.TabListener {
      public void onTabReselected(Tab tab, FragmentTransaction ft) {
          // Nothing
  
      }
      public void onTabSelected(Tab tab, FragmentTransaction ft) {
          mViewPager.setCurrentItem(tab.getPosition());
      }
  
      public void onTabUnselected(Tab tab, FragmentTransaction ft) {
      }
  }
  
  
  /*@Override
  public boolean onCreateOptionsMenu(Menu menu) {
  
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.kiste_main, menu);
      return true;
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
  
  
  
      int id = item.getItemId();
      if (id == R.id.action_settings) {
          Toast.makeText(this.getApplicationContext(), "YOU SHALL NOT PASS!!", Toast.LENGTH_SHORT).show();
          return true;
      }
      return super.onOptionsItemSelected(item);
  }
  
  @Override
  public boolean onPrepareOptionsMenu(Menu menu) {
      return super.onPrepareOptionsMenu(menu);
  }*/
  
  @Override
  public void libraryRefresh() {      
      /**
       * Tell adapter to update the views
       * content has changed
       */
      mPagerAdapter.notifyDataSetChanged();
  
      Toast.makeText(this, "Aktualisiert", Toast.LENGTH_SHORT).show();
  
  }
  
  
  @Override
  public void onFilmAdded() {
      /**
       * Tell adapter to update the views
       * content has changed
       */
      mPagerAdapter.notifyDataSetChanged();
      mViewPager.setCurrentItem(0);
      Toast.makeText(this, "Arbeit ist vollbracht", Toast.LENGTH_LONG).show();
  }
  
  
  @Override
  public void onFilmDeleted(String name) {
      mPagerAdapter.notifyDataSetChanged();
      mViewPager.setCurrentItem(0);
      Toast.makeText(this, name + " wurde verbannt.", Toast.LENGTH_LONG).show();
  }
  @Override
  public void onReturn() {
      mViewPager.setCurrentItem(0);
  }
  
  @Override
  public void onResume() {
      super.onResume();
      getWindow().setSoftInputMode(WindowManager.
              LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
  }
  </code></pre>
  
  <p><em>Fragment 1: LibraryFragment (Which is loaded by default)</em></p>
  
  <pre><code>public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
  
      // Inflate the layout for this fragment
      return inflater.inflate(R.layout.activity_bibliothek, container, false);
  }
  
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
  
      initialize();
  }
  
  public void onViewCreated(View view, Bundle savedInstanceState){
      super.onViewCreated(view, savedInstanceState);
  
      //View init here!
      listView = (ListView) view.findViewById(R.id.listView1);
      listView.setAdapter(adapter);
  
      listView.setOnItemLongClickListener(this);
  }
  
  
  private void initialize() {
  
      db = new DatabaseHelper(this.getActivity().getApplicationContext());
  
      valueList = new ArrayList&lt;Film&gt;();
      resList = new ArrayList&lt;String&gt;();
  
      valueList = db.getAllFilms();
  
  
      for(int i = 0; i &lt; valueList.size(); i++) {
          resList.add(valueList.get(i).getName());
      }
  
      adapter = new ArrayAdapter&lt;String&gt;(
              this.getActivity().getApplicationContext(), 
              android.R.layout.simple_list_item_1, resList);
  
      ad = new AlertDialog.Builder(this.getActivity())
      .setTitle("Löschen?")
      .setMessage("Der Film sollte nur gelöscht werden, wenn es keinen weiteren Teil gibt.")
      .setPositiveButton("Ja", this)
      .setNegativeButton("Nein", null);
  
  }
  
  public interface LibraryRefreshCallback {
      public void libraryRefresh();
  }
  
  private void refresh()  {
      //TODO UPDATE
      callback.libraryRefresh();
  
     // Toast.makeText(this.getActivity(), "Aktualisiert", Toast.LENGTH_SHORT).show();
  }
  
  @Override
  public void onAttach(Activity activity) {
          super.onAttach(activity);
          // Activities containing this fragment must implement its callbacks
          try{
              callback = (LibraryRefreshCallback) activity;
          }catch(ClassCastException e) {
              throw new ClassCastException(activity.toString()
                      + " must implement LibraryRefreshCallback");
          }
  
  }
  
  //popup onClick
  @Override
  public void onClick(DialogInterface arg0, int arg1) {
      //Created in @see onItemClick
      db.deleteFilm(film);
  
      refresh();
  
  }
  
  @Override
  public boolean onItemLongClick(AdapterView&lt;?&gt; arg0, View arg1, int arg2,
          long arg3) {
      String selectedFromList = (String) (arg0.getItemAtPosition(arg2));
  
      //System.out.println(selectedFromList);
      film = new Film();
      film.setName(selectedFromList);
      System.out.println("DEL: "+film.getName());
  
      //Show popup
      ad.show();
      return true;
  
  }
  </code></pre>
  
  <p><em>Fragment 2: add (which displays optionmenuitems from fragment 3 when called)</em></p>
  
  <pre><code>public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
  
      // Inflate the layout for this fragment
      return inflater.inflate(R.layout.activity_add_film, container, false);
  }
  
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      getActivity().invalidateOptionsMenu();
      setHasOptionsMenu(false);
  
  
      initialize();
  }
  
  public void onViewCreated(View view, Bundle savedInstanceState){
      super.onViewCreated(view, savedInstanceState);
  
      //View init here!
  
      btnSpeichern = (Button) view.findViewById(R.id.btn_add_film_speichern);
      btnSpeichern.setOnClickListener(this);
  
      editFilmName = (EditText) view.findViewById(R.id.edit_add_film_name);
  
  }
  
  
  
  private void initialize() {
      db = new DatabaseHelper(this.getActivity().getApplicationContext());
  
      ad = new AlertDialog.Builder(this.getActivity())
      .setTitle("Bestätigung")
      .setMessage("Wirklick speichern?")
      .setNegativeButton("Nein", null)
      .setPositiveButton("Ja", this);
  
  }
  
  @Override
  public void onClick(View v) {
      hideSoftKeyboard();
      ad.show();
  }
  
  private void hideSoftKeyboard() {
      imm = (InputMethodManager)getActivity().getSystemService(
                Context.INPUT_METHOD_SERVICE);
          imm.hideSoftInputFromWindow(editFilmName.getWindowToken(), 0);
  }
  
  @Override
  public void onClick(DialogInterface arg0, int arg1) {
      db.addFilm(editFilmName.getText().toString());
  
      //Film added; return to library.
  
      callback.onFilmAdded();
  
  }
  
  @Override
  public void onCreateOptionsMenu(
        Menu menu, MenuInflater inflater) {
      menu.removeItem(R.menu.kiste_random_film);
     //inflater.inflate(R.menu.kiste_main, menu);
  
  
      /*
       * ActionBar will display the TrashBin because it
       * prepares the next fragment (with its actionbar items)
       * 
       * TODO
       * find a way to hide
       */
      super.onCreateOptionsMenu(menu,inflater);
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
      // Handle presses on the action bar items
      switch (item.getItemId()) {
          default:
              return super.onOptionsItemSelected(item);
      }
  }
  
  public interface FilmAddedListener {
      public void onFilmAdded();
  }
  
  @Override
  public void onAttach(Activity activity) {
          super.onAttach(activity);
          // Activities containing this fragment must implement its callbacks
          try{
              callback = (FilmAddedListener) activity;
          }catch(ClassCastException e) {
              throw new ClassCastException(activity.toString()
                      + " must implement FilmAddedListener");
          }
  
  }
  
  public void setUserVisibibleHint(boolean isVisibleToUser) {
      super.setUserVisibleHint(isVisibleToUser);
  
      if(this.isVisible()) {
          if(!isVisibleToUser) {
              hideSoftKeyboard();
          }
      }
  }
  </code></pre>
  
  <p><em>Fragment 3: Which has an OptionMenu</em></p>
  
  <pre><code>public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
  
      // Inflate the layout for this fragment
      return inflater.inflate(R.layout.activity_zufalls_film, container, false);
  }
  
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
  
      initialize();
  }
  
  public void onViewCreated(View view, Bundle savedInstanceState){
      super.onViewCreated(view, savedInstanceState);
  
      //View init here!
      viewFilm = (TextView) view.findViewById(R.id.zufallsfilm_zufallsfilm);
  
      viewFilm.setText(film.getName().toString());
  
  }
  
  private void initialize() {
  
      db = new DatabaseHelper(this.getActivity().getApplicationContext());
  
      poolIDs = db.getAvailableFilmIDs();
  
      r = new Random();
  
      Log.i("POOL_SIZE",""+poolIDs.size());
  
      randNum = r.nextInt(poolIDs.size());
  
      Log.i("RANDOM_GEN",""+randNum);
      film = db.getFilm(poolIDs.get(randNum));
  
  
      ad = new AlertDialog.Builder(this.getActivity())
      .setTitle("Löschen?")
      .setMessage("Der Film sollte nur gelöscht werden, wenn es keinen weiteren Teil gibt.")
      .setNegativeButton("Nein", new OnClickListener() {
  
          @Override
          public void onClick(DialogInterface dialog, int which) {
              callback.onReturn();
          }
      })
      .setPositiveButton("Ja", this);
  
      ai = new AlertDialog.Builder(this.getActivity())
      .setTitle("Status")
      .setNeutralButton("OK", null);
  
  }
  
  
  private void handleBack() {
      ad.show();
  }
  
  @Override
  public void onClick(DialogInterface arg0, int arg1) {
      db.deleteFilm(film); //Can return boolean @see del
      callback.onFilmDeleted(film.getName());
  }
  
  @Override
  public void onResume() {
  
      super.onResume();
  
      getView().setFocusableInTouchMode(true);
      getView().requestFocus();
      getView().setOnKeyListener(new View.OnKeyListener() {
          @Override
          public boolean onKey(View v, int keyCode, KeyEvent event) {
  
              if (event.getAction() == KeyEvent.ACTION_UP &amp;&amp; keyCode == KeyEvent.KEYCODE_BACK){
  
                  handleBack();
  
                  return true;
  
              }
  
              return false;
          }
      });
  
    //To enable ActionBarItems
      if(isVisible()) {
          setHasOptionsMenu(true);
          getActivity().invalidateOptionsMenu();
      }
  }
  
  @Override
  public void onCreateOptionsMenu(
        Menu menu, MenuInflater inflater) {
      if(isVisible()) {
          inflater.inflate(R.menu.kiste_random_film, menu);
      }
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
      // Handle presses on the action bar items
      //isVisible() doesn't work the way I expected it.
   if(isVisible()) {
          switch (item.getItemId()) {
              case R.id.action_delete:
                  handleBack();
                  return true;
              default:
                  return super.onOptionsItemSelected(item);
          }
      }
      return super.onOptionsItemSelected(item);
  }
  
  
  public interface FilmDeletedListener {
      void onFilmDeleted(String name);
      void onReturn();
  }
  
  @Override
  public void onAttach(Activity activity) {
          super.onAttach(activity);
          // Activities containing this fragment must implement its callbacks
          try{
              callback = (FilmDeletedListener) activity;
          }catch(ClassCastException e) {
              throw new ClassCastException(activity.toString()
                      + " must implement FilmDeletedListener");
          }
  
  }
  </code></pre>
  
  <p><em>getItem(..) method from my MyPagerAdapter (extends FragmentStatePagerAdapter)</em></p>
  
  <pre><code>@Override
  public Fragment getItem(int index) {
      Log.d("MPA","SWITCHED TO POS "+ index);
  
      switch(index) {
      case 0:
          Log.d("MPA","RETURN LIB");
          return new LibraryFragment();
      case 1: 
          Log.d("MPA","RETURN NEW");
          return new SomethingNewFragment();
      case 2: 
          Log.d("MPA","RETURN RAN");
          return new ForGreatEntertainmentFragment();
      }
      return null;
  }
  </code></pre>