I am Replacing 2 Fragments One After another, and both fragments have different option menus. When I replace 2nd fragment it is showing menus of 1st fragment also. setHasOptionMenu(true); has set in both fragments.
I want to show only that option menu I am creating in particular fragment and Want to Avoid options of other fragments.
please help, Thanks
4 Answers
Answers 1
Just call invalidateOptionsMenu() on onCreate().
More reference check this one.
Hope this will help you.
Answers 2
This is how your activity will be
@Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { //your menu item return true; } return super.onOptionsItemSelected(item); // important line } In your fragment onCreateView() method
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); //imp line return inflater.inflate(R.layout.fragment_following, container, false); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.fragment_menu, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.action_1: // do stuff return true; case R.id.action_2: // do more stuff return true; } return false; } Answers 3
You can try creating different menu and naming it different from one used in first fragment. Alternatively you can also, try using the below code::
<item app:showAsAction="never" /> inside the switch case (when the particular fragment is selected) or if condition like when fragment 1 is selected do such thing and when fragment 2 is selected do such thing.
Answers 4
Just after replacing the fragment(or commiting the fragment transaction), you have to declare that option menu has changed, you can do so by calling invalidateOptionsMenu(). The onCreateOptionsMenu(Menu) method will be called the next time it needs to be displayed.
NOTE: you would need to call supportInvalidOptionsMenu in case if you are using AppCompat support library.
0 comments:
Post a Comment