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.
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.
Hide button by default in menu xml By default the share button will be hidden, as set by android:visible="false" .
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With