Passing URL from WebView to ShareActionProvider?

I want to use any page on which the user’s user is included in my WebView, and allow them to distribute the URL with FaceBook / etc as the intent ACTION_SEND.

I tried this, but obviously the url does not exist in onCreateOptionsMenu. How to transfer it to 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; } 
+4
source share
1 answer

Your code above does not work because onCreateOptionsMenu is called only once when the options menu is displayed.

Fixing this is pretty simple. We build our intent when onOptionsItemSelected is onOptionsItemSelected . This is when any bloated menu resource is selected. If the selected item is a shared resource, shareURL is shareURL , which now builds and runs Intent.

 @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Override public final boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_share: shareURL(); } return super.onOptionsItemSelected(item); } private void shareURL() { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, web.getUrl()); startActivity(Intent.createChooser(shareIntent, "Share This!")); } 

I have not tested the sample code above. Neither on the device itself, nor on the Java compiler. However, this should help you solve your problem.

+7
source

All Articles