Updated 6 March 2021
In this blog,
I will show you how to create a share button in the Action Bar of the MainActivity.
For implementing this we will use ShareActionProvider available in Android.
For creating share action, we have to do two things.
First, we have to need a menu item with property actionProviderClass having the value android.widget.ShareActionProvider.
Second thing is to set a share intent for this menu . This can be done in the callback function onCreateOptions.
Step 1:
Define the android:actionProviderClass attribute for the corresponding <item>
share_menu.xml
1 2 3 4 5 6 7 8 9 |
<menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_item_share" android:showAsAction="ifRoom" android:title="Share" android:actionProviderClass= "android.widget.ShareActionProvider" /> ... </menu> |
Step 2: Set the Share Intent
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
private ShareActionProvider mShareActionProvider; ... @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate menu resource file. getMenuInflater().inflate(R.menu.share_menu, menu); // Locate MenuItem with ShareActionProvider MenuItem item = menu.findItem(R.id.menu_item_share); // Fetch and store ShareActionProvider mShareActionProvider = (ShareActionProvider) item.getActionProvider(); // Return true to display menu return true; } // Call to update the share intent private void setShareIntent(Intent shareIntent) { if (mShareActionProvider != null) { mShareActionProvider.setShareIntent(shareIntent); } } |
Next, call MenuItem.getActionProvider()
to retrieve an instance of ShareActionProvider.
You may only need to set the share intent once during the creation of your menus, or you may want to set it and then update it as the UI changes.
Source:
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.