课程内容

  1. 使用新API实现Tabs
  2. Implement CompatTabHoneycomb
  3. Implement TabHelperHoneycomb

您还应该阅读

动手试试

下载示例代码
TabCompat.zip

这节课程将演示如何使用新的API来实现CompatTab和** TabHelper** 。该实现可以在支持新特性的系统上运行。

使用新API实现Tabs

通过_proxy代理_的方式来实现CompatTab 和 TabHelper 类。由于抽象的API和新的API是一样的,所以只要通过代理把对这些方法的调用委托给新的API即可。

在具体实现中您可以直接使用新的API,由于这些具体的实现类是延时加载的,所以当运行在旧的设备上时不会导致程序Crash。只要您不在3.0之前的系统上调用Honeycomb相关的具体实现,则 Dalvik VM 就不会 抛出 [VerifyError](http://developer.android.com/reference/java/lang/VerifyError.html) 异常。

好的命名策略就是使用具体的版本号对应的名称来命名,这样方便以后管理。由于这里的实现是基于3.0新功能的,所以我们的实现类名字就为CompatTabHoneycomb 和 TabHelperHoneycomb

backward-compatible-ui-classes-honeycomb
backward-compatible-ui-classes-honeycomb

Implement CompatTabHoneycomb

CompatTabHoneycomb 实现了 CompatTab 抽象类,该类的实现中只是把每个函数的调用委托给 ActionBar.Tab对象,该对象从Activity中获取。

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.)
}

Implement TabHelperHoneycomb

同样,TabHelperHoneycomb实现了TabHelper 抽象类。 函数的调用都委托给ActionBar对应的函数了。

public class TabHelperHoneycomb extends TabHelper {
    ActionBar mActionBar;
    ...

    protected void setUp() {
        if (mActionBar == null) {
            mActionBar = mActivity.getActionBar();
            mActionBar.setNavigationMode(
                    ActionBar.NAVIGATION_MODE_TABS);
        }
    }

    public void addTab(CompatTab tab) {
        ...
        // Tab is a CompatTabHoneycomb instance, so its
        // native tab object is an ActionBar.Tab.
        mActionBar.addTab((ActionBar.Tab) tab.getTab());
    }

    // The other important method, newTab() is part of
    // the base implementation.
}

原文:http://blog.chengyunfeng.com/?p=403