I want to take whatever page the user user is on in my WebView and allow them to share the URL with FaceBook/etc as a ACTION_SEND intent.
I tried this but obviously the URL doesn’t exist in the onCreateOptionsMenu. How can I move it to the onOptionsItemsSelected?
private ShareActionProvider mShareActionProvider;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
MenuItem item = menu.findItem(R.id.menu_item_share);
mShareActionProvider = (ShareActionProvider)item.getActionProvider();
mShareActionProvider.setShareHistoryFileName(
ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
mShareActionProvider.setShareIntent(createShareIntent());
return true;
}
private Intent createShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,
web.getUrl());
return shareIntent;
}
Your code above doesn’t work because
onCreateOptionsMenuis called only once, the first time the options menu is displayed.Fixing this is quite easy. We’re building our Intent when
onOptionsItemSelectedis called. This is when any resource of the inflated menu is selected. If the selected item is the share resource,shareURLis executed which now builds and starts the Intent.I didn’t test the code sample above. Neither on an actual device nor with the Java compiler. Nevertheless it should help you solving your problem.