CloseOptionsMenu doesn't work?

I only want to display the optionsMenu in a particular tab using the following code.

public class MainActivity extends FragmentActivity implements ActionBar.TabListener { /** * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the * three primary sections of the app. We use a {@link android.support.v4.app.FragmentPagerAdapter} * derivative, which will keep every loaded fragment in memory. If this becomes too memory * intensive, it may be best to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}. */ AppSectionsPagerAdapter mAppSectionsPagerAdapter; /** * The {@link ViewPager} that will display the three primary sections of the app, one at a * time. */ ViewPager mViewPager; private int currentPage = 0; public void onCreate(Bundle savedInstanceState) { // this.requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create the adapter that will return a fragment for each of the three primary sections // of the app. mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager()); // Set up the action bar. final ActionBar actionBar = getActionBar(); // Specify that the Home/Up button should not be enabled, since there is no hierarchical // parent. actionBar.setHomeButtonEnabled(false); actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayUseLogoEnabled(false); actionBar.setDisplayShowTitleEnabled(false); closeOptionsMenu(); // Specify that we will be displaying tabs in the action bar. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Set up the ViewPager, attaching the adapter and setting up a listener for when the // user swipes between sections. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mAppSectionsPagerAdapter); mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { // When swiping between different app sections, select the corresponding tab. // We can also use ActionBar.Tab#select() to do this if we have a reference to the // Tab. actionBar.setSelectedNavigationItem(position); currentPage = position; if (position == 2) { openOptionsMenu(); } else closeOptionsMenu(); } }); // For each of the sections in the app, add a tab to the action bar. for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title defined by the adapter. // Also specify this Activity object, which implements the TabListener interface, as the // listener for when this tab is selected. actionBar.addTab( actionBar.newTab() .setText(mAppSectionsPagerAdapter.getPageTitle(i)) .setTabListener(this)); } } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in the ViewPager. mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public boolean onCreateOptionsMenu(Menu menu) { //this method is used for adding menu items to the Activity // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary * sections of the app. */ public static class AppSectionsPagerAdapter extends FragmentPagerAdapter { public AppSectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { switch (i) { default: // The other sections of the app are dummy placeholders. Fragment fragment = new DummySectionFragment(); Bundle args = new Bundle(); args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1); fragment.setArguments(args); return fragment; } } @Override public int getCount() { return 3; } @Override public CharSequence getPageTitle(int position) { return "Section " + (position + 1); } } /** * A fragment that launches other parts of the demo application. */ public static class LaunchpadSectionFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_section_launchpad, container, false); // Demonstration of a collection-browsing activity. rootView.findViewById(R.id.demo_collection_button) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), CollectionDemoActivity.class); startActivity(intent); } }); // Demonstration of navigating to external activities. rootView.findViewById(R.id.demo_external_activity) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Create an intent that asks the user to pick a photo, but using // FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET, ensures that relaunching // the application from the device home screen does not return // to the external activity. Intent externalActivityIntent = new Intent(Intent.ACTION_PICK); externalActivityIntent.setType("image/*"); externalActivityIntent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); startActivity(externalActivityIntent); } }); return rootView; } } /** * A dummy fragment representing a section of the app, but that simply displays dummy text. */ public static class DummySectionFragment extends Fragment { public static final String ARG_SECTION_NUMBER = "section_number"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false); Bundle args = getArguments(); ((TextView) rootView.findViewById(android.R.id.text1)).setText( getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER))); return rootView; } } }

But it doesn't work. The optionsMenu are still there no matter which fragment is activated. (The currentPage in the code is always changed when switching tabs.)

<img src="https://i.stack.imgur.com/h0Ryv.png" alt="Options Menu">


If I got your question right.Each of your fragment should have enabled setHasOptionsMenu(true), if you want to have unique or action items at all per each.


The way you want to have an options menu in a particular tab fragment is not creating the options menu in the activity then hide/show it.

Instead of calling onCreateOptionsMenu() inside the Activity, call onCreateOptionsMenu() inside a fragment:

@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.main, menu); }

and don't forget to add this

@Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setHasOptionsMenu(true); }

to the fragment.


  • Casting a Menu Item in XML to a Spinner (Actionbar appcompat)
  • in Actionbar sherlock, add tab throw: commit already called
  • how to change swipe tabs text size for different screen size? I am using fragments and view pager to
  • android actionbar unit test using ActivityInstrumentationTestCase2
  • Adding title back to Android window when using PhoneGap
  • ActionBar and Fragments on ICS 4.0.3
  • How to revert changes on detached entities
  • Unable to attach multiple files to an email in Android
  • Dapper giving “Invalid attempt to call FieldCount when reader is closed.” when trying to use “QueryM
  • Through presenting new view controller viewWillDisappear on parent is triggered where I unsubscribe
  • How to reference a widget inside a specific tab of a QTabWidget?
  • Connect ipython-notebook via SSH tunnel from a remote location
  • How to enable sublime text to take first line as file name while saving?
  • how can we view symfony dump() output with ajax request?
  • XMLHttpRequest in IE-7
  • New Timeline Like Button Behavior
  • Controlling tab space in a using CSS?
  • Error when creating android project in eclipse
  • can't get In-App-Purchase hosted content to be actually hosted
  • Regex: Replace every Comma with Tab Not within quotes
  • Restart app on force kill
  • Adding Existing Group to Custom Ribbon in Office Word 2010
  • how to convert public key of an x509 certificate in JAVA to hex
  • How do I programatically open the Developer Tools' Console in a Firefox addon?
  • Opening links in a new tab and only the new tab
  • How do references in functions work?
  • How to avoid multiple definition of function (Linux, GCC/G++, Code::Blocks)
  • @DateTimeFormat not working properly
  • Reload UITableView from another tab
  • Keep same scale in different graphs ggplot2
  • Vue props data not updating in child component
  • Load image without autoscaling in Android
  • How do I recognize a line break with a switch case that evaluates a char in Java?
  • How to add System.Windows dll to Visual Studio 2010 express?
  • how to get data attributes of dynamically generated element
  • Outlines on links in IE9 remains when focus is changed
  • Array with custom indexes in Ionic2
  • Textfile Structure (tables)
  • Azure Cloud Service Web Role web pages do not load
  • How to push additional view controllers onto NavigationController but keep the TabBar?