从WebView传递URL到ShareActionProvider?

4
我希望能够在我的WebView中获取用户所在的页面,并允许他们通过ACTION_SEND意图与FaceBook等分享该URL。我已经尝试过这种方法,但显然URL并不存在于onCreateOptionsMenu中。如何将其移动到onOptionsItemSelected中?
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;
        }

只是一个提醒,我的意思是将其传递给onOptionsItemSelected,这样“url”将在页面加载后具有值。 - wilxjcherokee
1个回答

7
您上面的代码无法正常工作,因为onCreateOptionsMenu只在首次显示选项菜单时调用一次。
修复这个问题非常简单。当选择膨胀菜单的任何资源时,我们会在调用onOptionsItemSelected时构建我们的Intent。如果所选项目是共享资源,则会执行shareURL,现在构建并启动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!"));
}

我没有测试上面的代码示例。无论是在实际设备上还是使用Java编译器都没有进行过测试。尽管如此,它应该能帮助你解决问题。


谢谢你的回答!我明白你的意思,只是好奇小写意图是什么?我需要在其他地方创建它吗?编辑:算了,它可以工作了,非常感谢! - wilxjcherokee
抱歉,是我的错。意图 -> 分享意图 - ottel142

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接