本课程介绍如何创建 CompatTab
和 TabHelper
抽象类的子类并使用新 API。您的应用可以在支持这些 API 的平台版本的设备上使用此实现。
使用新 API 实现标签页
使用较新 API 的 CompatTab
和 TabHelper
具体类是一种代理实现。由于上一课中定义的抽象类与新 API(类结构、方法签名等)相对应,因此使用这些较新 API 的具体类只需代理方法调用及其结果。
由于类的延迟加载,您可以直接在这些具体类中使用较新的 API,而不会在早期设备上崩溃。类在首次访问时(首次实例化类或访问其静态字段或方法之一时)加载并初始化。因此,只要您不在 Honeycomb 之前的设备上实例化 Honeycomb 特定的实现,Dalvik VM 就不会抛出任何 VerifyError
异常。
此实现的一个良好命名约定是附加具体类所需的 API 级别或平台版本代号。例如,原生标签页实现可以由 CompatTabHoneycomb
和 TabHelperHoneycomb
类提供,因为它们依赖于 Android 3.0(API 级别 11)或更高版本中提供的 API。

图 1. Honeycomb 标签页实现的类图。
实现 CompatTabHoneycomb
CompatTabHoneycomb
是 CompatTab
抽象类的实现,TabHelperHoneycomb
使用它来引用单个标签页。CompatTabHoneycomb
只需将其包含的 ActionBar.Tab
对象的所有方法调用进行代理。
开始使用新的 ActionBar.Tab
API 实现 CompatTabHoneycomb
Kotlin
class CompatTabHoneycomb internal constructor(val activity: Activity, tag: String) : CompatTab(tag) { ... // The native tab object that this CompatTab acts as a proxy for. private var mTab: ActionBar.Tab = // Proxy to new ActionBar.newTab API activity.actionBar.newTab() override fun setText(@StringRes textId: Int): CompatTab { // Proxy to new ActionBar.Tab.setText API mTab.setText(textId) return this } ... // Do the same for other properties (icon, callback, etc.) }
Java
public class CompatTabHoneycomb extends CompatTab { // The native tab object that this CompatTab acts as a proxy for. ActionBar.Tab mTab; ... protected CompatTabHoneycomb(FragmentActivity activity, String tag) { ... // Proxy to new ActionBar.newTab API mTab = activity.getActionBar().newTab(); } public CompatTab setText(int resId) { // Proxy to new ActionBar.Tab.setText API mTab.setText(resId); return this; } ... // Do the same for other properties (icon, callback, etc.) }
实现 TabHelperHoneycomb
TabHelperHoneycomb
是 TabHelper
抽象类的实现,它将方法调用代理到实际的 ActionBar
,该 ActionBar
从其包含的 Activity
获取。
实现 TabHelperHoneycomb
,将方法调用代理到 ActionBar
API
Kotlin
class TabHelperHoneycomb internal constructor(activity: FragmentActivity) : TabHelper(activity) { private var mActionBar: ActionBar? = null override fun setUp() { mActionBar = mActionBar ?: mActivity.actionBar.apply { navigationMode = ActionBar.NAVIGATION_MODE_TABS } } override fun addTab(tab: CompatTab) { // Tab is a CompatTabHoneycomb instance, so its // native tab object is an ActionBar.Tab. mActionBar?.addTab(tab.getTab() as ActionBar.Tab) } }
Java
public class TabHelperHoneycomb extends TabHelper { ActionBar actionBar; ... protected void setUp() { if (actionBar == null) { actionBar = activity.getActionBar(); actionBar.setNavigationMode( ActionBar.NAVIGATION_MODE_TABS); } } public void addTab(CompatTab tab) { ... // Tab is a CompatTabHoneycomb instance, so its // native tab object is an ActionBar.Tab. actionBar.addTab((ActionBar.Tab) tab.getTab()); } // The other important method, newTab() is part of // the base implementation. }