我想使用 SDK 11 中包含的操作栏功能。不过,我还希望该应用程序能够在 SDK 10 (2.3.3) 的早期设备上运行。我愿意放弃早期设备的操作栏功能,因为它不是一个重要的功能。我已经阅读了所有关于反射、包装器类和其他一些技术的资料。我现在对如何使这项工作感到困惑。我正在使用 Eclipse。
如果我没有将 Eclipse 中的目标设置为 sdk 11 或更高版本,那么我引用 actionBar 的任何地方都会出现编译错误。如果我将目标设置为 sdk 11 或更高版本,它会编译但不会显示它可以在早期设备上运行。我一直设置 android:minSdkVersion=10
。
有人可以告诉我如何引用 actionBar
并使其指向以前的 sdk 级别吗?提前致谢。
最佳答案
是的!你绝对可以做到这一点。尝试遵循下面概述的模式。
在您的 AndroidManifest.xml
文件中声明以下内容(将平台版本替换为您的应用所需的任何内容):
<!-- Build Target -->
<uses-sdk android:targetSdkVersion="14" android:minSdkVersion="7" />
通过针对 API 11 或更高版本的平台版本,您允许 Eclipse 链接(编译)原生 ActionBar 类。提供较早的最低平台版本可让您的应用在较旧版本的 Android 上安装(运行)。
您的 Activity 代码应如下所示:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (CompatibilityManager.isHoneycomb()) {
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowHomeEnabled(true);
// ...
} else {
// The ActionBar is unavailable!
// ...
}
}
CompatibilityManager.java
类仅提供用于确定当前 SDK 版本的静态辅助方法:
public class CompatibilityManager {
public static final String KINDLE_FIRE_MODEL = "Kindle Fire";
/**
* Get the current Android API level.
*/
public static int getSdkVersion() {
return android.os.Build.VERSION.SDK_INT;
}
/**
* Determine if the device is running API level 11 or higher.
*/
public static boolean isHoneycomb() {
return getSdkVersion() >= Build.VERSION_CODES.HONEYCOMB;
}
/**
* Determine if the device is running API level 14 or higher.
*/
public static boolean isIceCreamSandwich() {
return getSdkVersion() >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
/**
* Determine if the current device is a first generation Kindle Fire.
* @return true if the device model is equal to "Kindle Fire", false if otherwise.
*/
public static boolean isKindleFire() {
return Build.MODEL.equals(KINDLE_FIRE_MODEL);
}
}
您还可以考虑利用 ActionBarSherlock库,它提供了一个兼容的 ActionBar API,一直到 Android 2.x:
The library will automatically use the native action bar when available or will automatically wrap a custom implementation around your layouts. This allows you to easily develop an application with an action bar for every version of Android back through 2.x.
玩得开心!
关于android - 如何在 Android SDK 中编写向后兼容的新功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9558638/