Search code examples
androidshareactionprovider

How to detect when user selects menu item with ShareActionProvider?


I have small problem with my Android app. I'm creating standard menu (using onCreateOptionsMenu). One of my menu elements is share button. This share element is using OnShareTargetSelectedListener to intercept which of the share options is clicked.

The problem is - I need to know if user clicks this "share" menu item (not share sub-element with all the sharing options like "Facebook", "Bluetooth", "Email" etc.). In onMenuItemSelected there is no call when "share" is clicked.

Is there any elegant way to intercept this "share" menu-element click event?


Solution

  • Ok, here is the solution: add new listener interface (ShareMenuListener.java):

    public interface ShareMenuListener {
        public void onMenuVisibilityChanged(boolean visible);
    

    }

    Extend ShareActionProvider (CustomShareActionProvider.java)

    public class CustomShareActionProvider extends ShareActionProvider {
    
    private ShareMenuListener mListener;
    
    public CustomShareActionProvider(Context context) {
        super(context);
    }
    
    @Override
    public void subUiVisibilityChanged(boolean isVisible) {
        super.subUiVisibilityChanged(isVisible);
        mListener.onMenuVisibilityChanged(isVisible);
    }
    
    public void setShareMenuListener(ShareMenuListener listener) {
        mListener = listener;
    }
    }
    

    Then in your activity or fragment, use CustomShareActionProvider instead of standard ShareActionProvider and implement ShareMenuListener interface. Implement onMenuVisibilityChanged method to perform custom action:

    @Override
    public void onMenuVisibilityChanged(boolean visible) {
        if(visible) {
            // Do your custom action here
        }
    }