代理至新的APIs

    这一课展示了如何编写CompatTab和TabHelper等抽象类的子类,并且使用了较新的APIs。你的应用可以在支持这些新的APIs的平台版本的设备上使用这种实现方式。

    CompatTab和TabHelper抽象类的具体子类是一种代理实现,它们使用了使用较新的APIs。由于抽象类在之前的课程中定义并且是对新APIs接口(类结构、方法签名等等)的镜像,使用新APIs的具体子类只是简单的代理方法调用和方法调用的结果。

    对于本实现,一个比较好的命名约定是把具体子类需要的API等级或者版本名字附加在APIs接口的后边。例如,本地tab实现可以由和abHelperHoneycomb这两个类提供,名字后面附加Honeycomb是由于它们都依赖于Android 3.0(API等级11)之后版本的APIs。

    • 图1. Honeycomb上tabs实现的类关系图.

    TabHelperHoneycombTabHelper抽象类的具体实现,TabHelperHoneycomb代理方法调用到ActionBar对象,而这个ActionBar对象是从包含他的中获取的。

    实现TabHelperHoneycomb,代理其方法调用到ActionBar的API:

    1. public class TabHelperHoneycomb extends TabHelper {
    2. ...
    3. if (mActionBar == null) {
    4. mActionBar = mActivity.getActionBar();
    5. mActionBar.setNavigationMode(
    6. ActionBar.NAVIGATION_MODE_TABS);
    7. }
    8. }
    9. public void addTab(CompatTab tab) {
    10. // Tab is a CompatTabHoneycomb instance, so its
    11. // native tab object is an ActionBar.Tab.
    12. mActionBar.addTab((ActionBar.Tab) tab.getTab());
    13. }
    14. // The other important method, newTab() is part of
    15. // the base implementation.