分享动作按钮 - 动作栏|不工作

时间:2016-03-09 16:20:57

标签: java android android-actionbar shareactionprovider share-button

分享菜单项

<item
    android:id="@+id/action_share"
    android:title="@string/action_share"
    android:orderInCategory="2"
    app:showAsAction="ifRoom"
    android:actionProviderClass="android.widget.ShareActionProvider" />

MainActivity.java

@覆盖

public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_main, menu);
    MenuItem menuItem = menu.findItem(R.id.action_share);
    shareActionProvider = (ShareActionProvider) menuItem.getActionProvider();
    setIntent("This is a sample text");
    return true;
}

private void setIntent(String string)
{
    Intent intent = new Intent(android.content.Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(android.content.Intent.EXTRA_TEXT,string);
    shareActionProvider.setShareIntent(intent);
}

@覆盖

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_share)
    {

    }

这根本不起作用,应用程序崩溃了。

logcat是 -

03-09 21:38:46.567 30763-30763/? E/AndroidRuntime: FATAL EXCEPTION: main
   Process: com.example.pooja1.bitsandpizzas, PID: 30763
   java.lang.UnsupportedOperationException: This is not supported, use MenuItemCompat.getActionProvider()
       at android.support.v7.view.menu.MenuItemImpl.getActionProvider(MenuItemImpl.java:645)
       at com.example.pooja1.bitsandpizzas.MainActivity.onCreateOptionsMenu(MainActivity.java:31)
       at android.app.Activity.onCreatePanelMenu(Activity.java:2862)
       at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:341)

MainActivity.java:31 - &gt;行shareActionProvider = (ShareActionProvider) menuItem.getActionProvider();

提前致谢!

2 个答案:

答案 0 :(得分:0)

很明显,它是在使用

的例外中写的
MenuItemCompat.getActionProvider()

由android v7提供支持库而不是使用

menuItem.getActionProvider();

默认android提供的方法。

答案 1 :(得分:0)

尝试将android:actionProviderClass="android.widget.ShareActionProvider"更改为app:actionProviderClass="android.support.v7.widget.ShareActionProvider"