1

I have been struggling to implement switching visibility of Share option on Menu between fragments. I am using sliding tab layout and has a fragment in each of the 2 tabs. First tab (uses list view) and when an item is selected, I am setting a flag as true and calls invalidateOptionsMenu() and it works fine by showing a share option on the App bar menu, but I am not able to cancel it when I move to the other fragment which has mainly preferences. Code is similar to the below.

public void setSharedIntentText(String text) {
sharedText = text;
if (shareOptionVisibility == false) {
    shareOptionVisibility = true;
    invalidateOptionsMenu();
}


public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem shareItem = menu.findItem(R.id.menu_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, sharedText);
mShareActionProvider.setShareIntent(sendIntent);
shareItem.setVisible(shareOptionVisibility);

When I switch between tabs, visibility should be set appropriately. I tried to set it onPause method of the first fragment, and then onResume method of second fragment, but control doesn't seem to go these methods when I look at the logcat. The code I have used to set visibility to false is as below in fragment2.

public void onResume() {
 super.onResume();
 Log.i(TAG, "On Resume ");
 ((MainActivity) getActivity()).shareOptionVisibility = false;
 ((MainActivity) getActivity()).invalidateOptionsMenu(); 
}

So would like to know where is the best place to put the code to control visibility when we switch between tabs. Here are the list of classes I use. MainActivity, fragment1, fragment2, SlidingTabLayout, SlidingTabStrip and ViewPagerAdaptor. This code was implemented on top of the com.example.android.actionbarcompat.shareactionprovider example.

Thanks in advance

1 Answers1

0

Issue now resolved by implementing the onCreateOptionsMenu method from the fragment rather than from the MainActivity. Thanks