0

我在实现菜单以共享我的应用程序时遇到问题。当我打开具有图标 share_button 的活动时,会立即显示“共享方式”对话框。我认为我对这行代码“startActivity(Intent.createChooser(shareIntent(),“Share ...”))有问题;”

这是我的代码

private ShareActionProvider mShareActionProvider;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.mainpage, menu);
    MenuItem item = menu.findItem(R.id.menu_item_share);

    mShareActionProvider = (ShareActionProvider) item.getActionProvider();
    mShareActionProvider.setShareHistoryFileName(null);
    // Create the share Intent
    String playStoreLink = "https://play.google.com/store/apps/details?id=" +
        getPackageName();
    String yourShareText = "Install this app " + playStoreLink;
    Intent shareIntent = ShareCompat.IntentBuilder.from(this)
        .setType("text/plain").setText(yourShareText).getIntent();
    // Set the share Intent
    mShareActionProvider.setShareIntent(shareIntent);
    startActivity(Intent.createChooser(shareIntent(), "Share via"));
    return true;
}

菜单项

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:id="@+id/menu_item_share"
    android:showAsAction="ifRoom"
    android:title="Share"
    android:icon="@drawable/ic_share"
    android:actionProviderClass="android.widget.ShareActionProvider" />

4

2 回答 2

0

像这样改变你的代码

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.mainpage, menu);
    MenuItem item = menu.findItem(R.id.menu_item_share);

    mShareActionProvider = (ShareActionProvider) item.getActionProvider();
    mShareActionProvider.setShareHistoryFileName(null);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    switch (item.getItemId()) {
    case R.id.menu_item_share:


    String playStoreLink = "https://play.google.com/store/apps/details?id=" +
    getPackageName();
    String yourShareText = "Install this app " + playStoreLink;
    Intent shareIntent = ShareCompat.IntentBuilder.from(this)
        .setType("text/plain").setText(yourShareText).getIntent();
    // Set the share Intent
    mShareActionProvider.setShareIntent(shareIntent);
    startActivity(Intent.createChooser(shareIntent(), "Share via"));
        break;

    default:
        break;
    }

    return super.onOptionsItemSelected(item);
}
  • onCreateOptionsMenu当您的活动调用时会调用。
  • 您需要在按下时启动共享意图Share button`
  • 所以调用 share IntentonOptionsItemSelected
于 2013-07-30T05:17:32.057 回答
0

您必须将这行代码startActivity(Intent.createChooser(shareIntent(), "Share via"));移出到按钮单击处理程序或菜单选择处理程序中。

将调用该函数onCreateOptionsMenu()来设置菜单,这将在您Activity启动时发生。

于 2013-07-30T05:20:04.287 回答