Tutorials Xamarin ShareActionProvider Example in Xamarin.Android

ShareActionProvider Example in Xamarin.Android

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

Total
0
Shares
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Gregz
Gregz
6 years ago

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

Previous Post
Android Tutorials

How to Apply Shadow Effect on Android TextView

Next Post

Action Bar Tabs Example in Xamarin

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
1
0
Would love your thoughts, please comment.x
()
x