我想在我的项目中实现共享操作,但是当我使用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; }
解决方法
我相信你已经为你的活动分类了AppCompatActivity,因为你得到了这个错误,请使用下面的代码
在您的活动中初始化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视图的样子
<item android:id="@+id/action_share" app:actionProviderClass="android.support.v7.widget.ShareActionProvider" app:showAsAction="always" android:title="Share" />
请确保你的SDK更新,在这个特殊的情况下,我确实碰到了,当你不知道缺少什么时,这是令人讨厌的