![](/img/trans.png)
[英]ActionBar Compat ActionBarActivity setTitle does not work in Android 2.X
[英]Error in Android 2.x after setting the ActionBar
嗨,大家好,我在MainActivity.java中设置了此代码,以在应用程序上添加共享按钮。 我知道操作栏在早期的android版本上无法正常工作。 一位装有android 2.3的客户告诉我,当他按下电话菜单按钮时,应用程序崩溃并被迫关闭。 从3.0版到更高版本,一切正常,您会看到“共享”按钮。 我可以在此功能之前添加一些代码行来覆盖o如果Android版本低于3.0,则阻止使用共享按钮操作?
这是我的代码中的内容:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
MenuItem shareItem = (MenuItem) menu.findItem(R.id.action_share);
ShareActionProvider mShare = (ShareActionProvider)shareItem.getActionProvider();
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Download here https://www.apps.com");
mShare.setShareIntent(shareIntent);
return true;
}
我的menu.xml文件具有以下内容(显示图标,可以正常运行):
<item android:id="@+id/action_share" android:title="@string/menu_share"
android:icon="@drawable/menu_share" android:showAsAction="ifRoom"
android:actionProviderClass="android.widget.ShareActionProvider"></item>
在Android 2.x中无法立即使用ActionBar。 发生崩溃是因为MenuItem无法理解getActionProvider()
,它是API 14(Android 4.0 Ice Cream Sandwich)中引入的。
您有两种选择:
这是可以避免在2.x设备上崩溃的方法。 通过检查设备是否正在运行Ice Cream Sandwich或更高版本来保护使用较新的API:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
MenuItem shareItem = (MenuItem) menu.findItem(R.id.action_share);
ShareActionProvider mShare = (ShareActionProvider)shareItem.getActionProvider();
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Download here https://www.apps.com");
mShare.setShareIntent(shareIntent);
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.