I have an ActionBar action with FrameLayout and a menu. when the user clicks a menu item, I replace the fragment with the corresponding new fragment. However, I do not see an obvious way to remove the menu item for the selected fragment.
public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { StudyFragment startFragment = new StudyFragment(); startFragment.setArguments(getIntent().getExtras()); getSupportFragmentManager().beginTransaction().add (R.id.container, startFragment).commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.action_study: replaceFragment((Fragment)new StudyFragment()); break; case R.id.action_list: replaceFragment((Fragment)new ListFragment()); break;
The Google documentation on changing the menu says disabling the menu in onPrepareOptionsMenu - but how do I know which item was selected?
- Implemented solution -
Using the Muhammed Refaat solution below, I added two new members to the class:
private Menu activityMenu; private MenuItem curMenuItem;
Set them to onCreateOptionsMenu
activityMenu = menu; curMenuItem = activityMenu.findItem(R.id.action_study); curMenuItem.setVisible(false);
And changed them to onOptionsItemSelected
curMenuItem.setVisible(true); curMenuItem = activityMenu.findItem(id); curMenuItem.setVisible(false);
source share