Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide/Show Action Bar Option Menu Item for different fragments

I have a Sherlock Fragment Activity in which there are 3 Fragments.

Fragment A, Fragment B, Fragment C are three fragments. I want to show a done option menu in Fragment B only.

And the activity is started with Fragment A. When Fragment B is selected done button is added.

@Override public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setHasOptionsMenu(true); }  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {     if(!menusInflated){         inflater.inflate(R.menu.security, menu);         menusInflated=true;     }      super.onCreateOptionsMenu(menu, inflater); } 

When I again start Fragment A I want to options Menu DONE (which was set at Fragment B) for this I am doing like this

setHasOptionsMenu(false); MenuItem item = (MenuItem) menu.findItem(R.id.done_item); item.setVisible(false); 

But this is not hiding at all, also it is giving NullPointerException when Activity if first started with Fragment A.

Please let me know what is the problem.

like image 805
Gaurav Arora Avatar asked Apr 20 '14 05:04

Gaurav Arora


People also ask

How do we hide the menu on toolbar in one fragment?

When you click the hide button to hide the fragment. The fragment menu items disappear from the action bar also. You can also click back menu to exit the fragment and the activity.

How do I hide a menu item?

Hide button by default in menu xml By default the share button will be hidden, as set by android:visible="false" .

How can we send some data from one fragment to another?

Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 3 − Create two FragmentActivity and add the codes which are given below.


1 Answers

Try this...

You don't need to override onCreateOptionsMenu() in your Fragment class again. Menu items visibility can be changed by overriding onPrepareOptionsMenu() method available in Fragment class.

 @Override public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setHasOptionsMenu(true); } @Override public void onPrepareOptionsMenu(Menu menu) {     menu.findItem(R.id.action_search).setVisible(false);     super.onPrepareOptionsMenu(menu); } 
like image 132
Silambarasan Poonguti Avatar answered Sep 19 '22 16:09

Silambarasan Poonguti