Adding Share Action on Android Application ActionBar (appcompat v7)

Adding share action on android application action bar is simple and straight forward.

There are mainly 3 steps that you have to follow:

1. Add Share Action Item in your menu

To add share action item in your menu simply add below item in your menu layout:

	app:actionProviderClass="" />

And don’t forget to add res-auto schema on your menu. Your final menu layout should contain below details:

<menu xmlns:android=""
		app:actionProviderClass="" />
You can set showAsAction to any other value like always, never, withText etc

2. Create ShareActionProvider in your activity

No you have to create ShareActionProvider in your activity where you want to show and handle action share event.

For that first declare ShareActionProvider object

private ShareActionProvider mShareActionProvider;

override onCreateOptionMenu in your activity and add below code:

public boolean onCreateOptionsMenu(Menu menu) 
	// Inflate menu resource file.
	getMenuInflater().inflate(, menu);

	// Locate MenuItem with ShareActionProvider
	MenuItem item = menu.findItem(;

	// Fetch and store ShareActionProvider
	mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);

	// Return true to display menu
	return true;

Here menu_main should be your menu xml file name and menu_item_share is the id of share item added in the menu.

You many notice that we have called a method setShareIntent at the end just before returning. This is not an inbuilt method. We will define this in next step.

3. Set Share Intent

Here we will set the intent of the share action so that we can control what will be shared if user proceeds to go further with sharing.

private void setShareIntent() 
	if (mShareActionProvider != null) 
		Intent myShareIntent = new Intent(Intent.ACTION_SEND);

		myShareIntent.putExtra(Intent.EXTRA_SUBJECT, "");
		myShareIntent.putExtra(Intent.EXTRA_TEXT, "");


You can specify different share intent type like in our case we have set text/plain because we are sharing plain text. Similarly you can set other type like view, images etc.

After that put extras based on based on your share intent type. For text/plain we have set subject and text.

Note: Whenever in your activity life cycle if your share content (subject and text in our case) is changed just call this method setShareIntent, no need to create ShareActionProvider again.

Leave a Reply