gpt4 book ai didi

android - 如何在android中实现分享 Action ?

转载 作者:塔克拉玛干 更新时间:2023-11-02 18:59:53 26 4
gpt4 key购买 nike

我想在我的项目中实现共享操作,但是当我使用 MenuItem 时,它会出现运行时错误,而改用 MenuItemCompat,但它也会出现错误。

这是我的代码:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_third_, menu);
MenuItem menuItem = menu.findItem(R.id.menu_item_share);


mShareActionProvider = (ShareActionProvider) menuItem.getActionProvider();

mShareActionProvider.setShareIntent(getDefaultShareIntent());

return true;
}

public Intent getDefaultShareIntent (){

Intent shareIntent = new Intent(Intent.ACTION_SEND);

shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "SUBJECT");
shareIntent.putExtra(Intent.EXTRA_TEXT,"Extra Text");
return shareIntent;
}

最佳答案

我相信您已为您的 Activity 子类化 AppCompatActivity,因此您会收到此错误,请使用以下代码

在您的 Activity 中初始化 ShareActionProvider

import android.support.v7.widget.ShareActionProvider;
import android.support.v4.view.MenuItemCompat;


private ShareActionProvider mShareActionProvider;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.action_share);

// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);

mShareActionProvider.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
// Set share Intent.
// Note: You can set the share Intent afterwords if you don't want to set it right now.
mShareActionProvider.setShareIntent(createShareIntent());
// Return true to display menu
return true;
}

// Create and return the Share Intent
private Intent createShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "http://play.google.com/store/apps/details?id=pk.nimgade.Bostan.Train.Schedule");
Intent intent = Intent.createChooser(shareIntent,"Share");
return shareIntent;
}

这就是您的 xml View 的样子

 <item
android:id="@+id/action_share"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
app:showAsAction="always"
android:title="Share" />

请确保您的 SDK 已更新,在这种特殊情况下我确实遇到过,当您不知道缺少什么时这很糟糕

关于android - 如何在android中实现分享 Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33593481/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com