0%

Android开发:创建向后兼容的UI--代理新API

代理新API 翻自http://developer.android.com/training/backward-compatible-ui/new-implementation.html#compattabhoneycomb 本课向你展示了如何继承CompatTab和TabHelper抽象类,并且使用新API,你的应用可以在支持他们的平台上使用这个实现。 用新的API实现Tab 用新API实现CompatTab和TabHelper的实现类是代理实现。前面介绍了定义抽象类,复制新API(类结构,方法等),实现类简单地代理使用新API,并返回他们的结果. 你可以在这些实现类中直接使用新API,并且在早期版本中不会Crash,因为懒加载。类在第一次访问实例化类或一个静态字段或方法时被载入和初始化。因此,只要你不在Honeycomb之前的版本实例化Honeycomb专有的实现,Dalvik虚拟机不会有任何验证错误异常. 一个良好的实现命名约定是加上API版本或者平台版本。比如,本地tab实现可以命名为CompatTabHoneycomb和TabHelperHoneycomb,因为他们依赖于Android 3.0或以上版本 实现CompatTabHoneycomb CompatTabHoneycomb是CompatTab抽象类的一个实现,TabHelperHoneycomb用它来引用独立标签。CompatTabHoneycomb简单地代理了所有方法调用给它代理的ActionBar.Tab对象

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的实现,用来代理方法调用到一个从Activity上获取的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.
}