将共享操作添加到android WebView片段

将共享操作添加到android WebView片段,android,android-fragments,android-webview,share,shareactionprovider,Android,Android Fragments,Android Webview,Share,Shareactionprovider,我知道这个问题以前被问过很多次,我也尝试过很多答案,但都不适合我,所以这是我的问题。我有一个使用WebView的android应用程序,之前我在活动中使用WebView,添加共享页面当前URL链接的共享操作很容易,但在最近的更新中,我在片段中添加了WebView,现在我无法在该片段中添加共享操作。正如我添加的按钮,它显示在行动栏上,但它不响应点击。以下是我的代码 main.xml <item android:id="@+id/menu_item_share" android

我知道这个问题以前被问过很多次,我也尝试过很多答案,但都不适合我,所以这是我的问题。我有一个使用WebView的android应用程序,之前我在活动中使用WebView,添加共享页面当前URL链接的共享操作很容易,但在最近的更新中,我在片段中添加了WebView,现在我无法在该片段中添加共享操作。正如我添加的按钮,它显示在行动栏上,但它不响应点击。以下是我的代码

main.xml

<item android:id="@+id/menu_item_share"
        android:icon="@drawable/ic_menu_share"
        android:title="@string/menu_item_share"
        app:showAsAction="always"/>
在MainActivity.java中共享操作

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            //share app content
            case R.id.menu_item_share: {
                Intent shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.setType("text/plain");
                shareIntent.putExtra(Intent.EXTRA_TEXT, myWebView.getUrl());
                startActivity(Intent.createChooser(shareIntent, "Share This Website!"));
                shareIntent.setPackage("com.whatsapp");
                break; //or, return true;
            }

请帮助解决此问题。

只有在将工具栏注册为actionbar后,才能使用actionbar菜单

在主要活动中:

Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);

您的工具栏现在应该响应菜单中的操作。

在片段类中使用这些方法,并在这些方法中添加共享功能:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Do something that differs the Activity's menu here
super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {

    case R.id.activity_menu_item:

        // Not implemented here
        return false;
    case R.id.fragment_menu_item:

        // Do Fragment menu item stuff here
        return true;

    default:
        break;
}

return false;
}
在片段的“OnCreateView()”方法中添加以下行:

setHasOptionsMenu(true);

希望它能起作用

我已经这样做了,操作栏上的其他选项没有链接到webview,但效果很好,只是共享操作不起作用。它起作用了,这是我在数百次搜索后得到的最简单、最准确的解决方案。
setHasOptionsMenu(true);