(二)进阶练习____10、创建向下兼容UI——通过代理实现新的API

负责人:ziggurat

原文链接:http://docs.eoeandroid.com/training/backward-compatible-ui/abstracting.html

目录

 [隐藏

通过代理实现新的API

这节课程我们讲述如何用新的API实现CompatTab和TabHelper两个抽象类,我们的应用将能够在支持他们的平台上使用这两个抽象类的实现。

 

用新的API实现Tabs

用新版本API实现CompatTab和TabHelper实际上是一种代理模式的实现,因为上一节课程中创建的抽象类映射了新的APIs(类结构,方法语句等.),实现类只需要简单的代理新APIs中的方法和返回结果。

我们可以直接使用这些新的APIs,因为有类的延迟加载,他们在旧版本中不会产生崩溃。类在第一次访问实例化时,或者类的静态属性或方法第一次被访问时才会加载并初始化。因此,只要我们没有在Honeycomb之前版本的设备上实例化Honeycomb的特定实现,Dalvik 虚拟机就不会抛出任何VerifyError异常。

对于这种实现方法一个比较好的命名规范是,把API Level或者与API一致的平台版本名字添加在类名中,例如本地化的实现类CompatTabHoneycomb 和TabHelperHoneycomb ,因为他们依赖于在Android 3.0 (API level 11) 或者更新的版本中使用的APIs。

Backward-compatible-ui-classes-honeycomb.png

图1:Honeycomb 实现tabs的类结构图

实现CompatTabHoneycomb类

CompatTabHoneycomb是抽象类CompatTab的实现,TabHelperHoneycomb用来引用单个Tabs,CompatTabHoneycomb简单的代理ActionBar.Tab的所有调用方法。

下面开始使用ActionBar.Tab的API实现CompatTabHoneycomb: 

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的方法。

下面实现了TabHelperHoneycomb,通过代理方法调用ActionBar API:

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

 

 

 
posted @ 2014-07-30 17:24  ╰→劉じ尛鶴  阅读(117)  评论(0)    收藏  举报