Skip to content

Instantly share code, notes, and snippets.

@seemike
Last active December 21, 2015 22:39
Show Gist options
  • Save seemike/6377186 to your computer and use it in GitHub Desktop.
Save seemike/6377186 to your computer and use it in GitHub Desktop.
Android 4.0 share items on action bar (API Level 14 ICS )
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/action_share"
android:title="@string/action_share"
android:showAsAction="ifRoom"
android:actionProviderClass="android.widget.ShareActionProvider"
/>
</menu>
public static final String SHARE_URL = "shareUrl";
public static final String SHARE_TITLE = "shareTitle";
private ShareActionProvider mShareActionProvider;
private String shareUrl;
private String shareTitle;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.actions, menu);
// return true;
// Set up ShareActionProvider's default share intent
MenuItem shareItem = menu.findItem(R.id.action_share);
mShareActionProvider = (ShareActionProvider) shareItem.getActionProvider();
/** Defines a default (dummy) share intent to initialize the action provider.
* However, as soon as the actual content to be used in the intent
* is known or changes, you must update the share intent by again calling
* mShareActionProvider.setShareIntent()
*/
setShareInfo(this.shareUrl, this.shareTitle);
return super.onCreateOptionsMenu(menu);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set defaults and recover on orientation change
this.shareUrl = getString(R.string.share_defaulturl);
this.shareTitle = getString(R.string.share_defaulttitle);
if(null != savedInstanceState){
this.shareUrl = savedInstanceState.getString(SHARE_URL, this.shareUrl);
this.shareTitle = savedInstanceState.getString(SHARE_TITLE, this.shareTitle);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString(SHARE_URL, shareUrl);
outState.putString(SHARE_TITLE, shareTitle);
super.onSaveInstanceState(outState);
}
/**
* call that method when the sharing data is set (onCreate, inResume, datacallback..)
*/
public void setShareInfo(String url, String title) {
Log.d(LOG_TAG, "set share info. url: " + url + " title: " + title);
this.shareUrl = url;
this.shareTitle = title;
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.share_message_text, title, url));
intent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.share_message_subject, title));
if (null != mShareActionProvider)
mShareActionProvider.setShareIntent(intent);
else Log.w(LOG_TAG, "shareActionProvider is null");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment