This example explains how to implement “share action in your action bar using ShareActionProvider class”. ActionProvider is made available since Android 4.0 (API Level 14). An ActionProvider, once attached to a menu item in the action bar, handles both the appearance and behavior of that item. In the case of ShareActionProvider, you provide a share intent and it does the rest.

Specifying the action Provider Class

To use the ShareActionProvider, set the android:actionProviderClass attribute on a menu item in the XML for the Action Bar’s menu.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@+id/shareMenu"
      android:showAsAction="always"
      android:title="Share"
      android:actionProviderClass="android.widget.ShareActionProvider" />
</menu>

Your activity class

using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace ShareActionProviderExample
{
	[Activity (Label = "ShareActionProviderExample", MainLauncher = true)]
	public class MainActivity : Activity
	{
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			TextView tv = new TextView (this);
			tv.Text = "This is an ShareActionProvider Example";
			tv.SetPadding (20, 20, 20, 20);

			// Set our view from the "main" layout resource
			SetContentView (tv);
		}

		public override bool OnCreateOptionsMenu (IMenu menu) {

			MenuInflater.Inflate (Resource.Menu.MainMenu, menu);   

			var shareMenuItem = menu.FindItem (Resource.Id.shareMenu);           
			var shareActionProvider =
				(ShareActionProvider)shareMenuItem.ActionProvider;
			shareActionProvider.SetShareIntent (CreateIntent ());

			return true;
		}

		Intent CreateIntent () {  
			var sendPictureIntent = new Intent (Intent.ActionSend);
			sendPictureIntent.SetType ("image/*");
			var uri = Android.Net.Uri.FromFile (GetFileStreamPath ("image.png"));          
			sendPictureIntent.PutExtra (Intent.ExtraStream, uri);
			return sendPictureIntent;
		}
	}
}

Output

ShareActionProvider Example in Xamarin

Stacktips

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages. Follow us on Twitter

Related Articles

Join The Discussion

Please note: We reserve the right to delete comments that contains snarky remarks, offensive or off-topic. To know more read our comments policy.
  • Gregz

    Really? So simple? Thanks… You have very usefull posts.