我有一个应用,我想添加一个分享按钮。单击按钮后,我希望它打开以下窗口:
然后用户将选择共享它的位置,它将显示以下默认消息: “刚刚找到这个很棒的应用程序!在这里找到它:https://play.google.com/store/apps/details?id=com.ideashower.readitlater.pro”
你能告诉我怎么做吗?
答案 0 :(得分:30)
启动SEND意图时,通常应将其包装在选择器中(通过createChooser(Intent, CharSequence)),这将为用户提供适当的界面,以便选择如何发送数据并允许您指定提示他们在做什么。
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
# change the type of data you need to share,
# for image use "image/*"
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, URL_TO_SHARE);
startActivity(Intent.createChooser(intent, "Share"));
如果您只想在“溢出”菜单中添加“共享”按钮,请查看ShareActionProvider。
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.share, menu);
MenuItem item = menu.findItem(R.id.share_item);
actionProvider = (ShareActionProvider) item.getActionProvider();
// Create the share Intent
String shareText = URL_TO_SHARE;
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
.setType("text/plain").setText(shareText).getIntent();
actionProvider.setShareIntent(shareIntent);
return true;
}
希望这会有所帮助。 :)
答案 1 :(得分:3)
正如Android开发者在此链接中所述:http://developer.android.com/training/sharing/shareaction.html
你必须添加这个菜单项:
<item
android:id="@+id/menu_item_share"
android:showAsAction="ifRoom"
android:title="Share"
android:actionProviderClass=
"android.widget.ShareActionProvider" />
然后在Activity中添加以下代码:
private ShareActionProvider mShareActionProvider;
...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.share_menu, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}