Reputation: 61
I have a diferent fragments but I want to change the options menu. I want that only the "Solicitudes" have it
The fragment that I want to have this option
This fragment shouldn't have it
I have a menu folder with the main.xml and actually I create another main2.xml that doesn't have this settings option but I don't know how to change this
Here's my code so far:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mTitle = mDrawerTitle = getTitle();
fragment = new History();
The oncreate:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
And the code for the History fragment:
public class History extends Fragment {
public static final String ARG_HISTORY = "arg_history";
public History() {
// Empty constructor required for fragment subclasses
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.history, container, false);
return rootView;
}
Upvotes: 1
Views: 2944
Reputation: 16231
In your Fragment
you need to say that this Fragment
controls the menu.
In your Fragment
's onCreate
.
setHasOptionsMenu(true);
Now you can implement the following in your Fragment
to hide the MenuItem
you don't want.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.findItem(R.id.unwanted_item).setVisible(false);
}
Make sure you do the reverse in the Fragment
you do want the MenuItem
in.
If you want to add a MenuItem
that is not in the Menu
loaded by your Activity
do the following in the onCreateOptionsMenu
in your Fragment
.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_to_add_to_original, menu);
super.onCreateOptionsMenu(menu, inflater);
}
Upvotes: 3