0%

Android开发:创建向后兼容的UI–创建旧版API的实现

翻自http://developer.android.com/training/backward-compatible-ui/older-implementation.html 本课讨论如何创建一个反应新的API,还支持旧设备的实现。 选定一个替代方案 在使用新的UI特性又要保持向后兼容时,最大的挑战是选定旧平台上的实现。很多情况下,可以满足使用旧的框架特性,而使用新UI组件的目的。如: ActionBar可以用一个水平的LinearLayout,包含图片按钮,自定义的标题栏,或者作为一个Activity布局的视图。Overflow actions(右上角三个点,点击弹菜单)可以通过设备的菜单按钮实现。 ActionBar标签可以使用水平LinearLayout包含按钮来实现,或者使用TabWidget NumberPicker和Switch widgets可以用Spinner和ToggleButton分别实现。 ListPopupWindow和PopupMenu可以用PopupWindow实现 用新UI适配老设备,没有通用的方案。考虑到用户体验:在老设备上,用户可能对新设计模式和UI组件不熟悉。多想想如何用用户熟悉的元素跳到相同的功能。很多情况下,这样做需要关注更少(如果新的UI组件在应用生态系统中是突出的,像ActionBar,或者交互模型是简单直观的,像ViewPager滑动page) 使用旧API实现Action Bar Tab,你可以用TabWidget和TabHost(虽然也可以使用水平布局的按钮).在命名为TabHelperEclair和CompatTabEclair的类中实现,因为这个实现用了Android 2.0(Eclair)中引用的api. Eclair实现类图: CompatTabEclair实现保存tab属性,像实例中的tab的文本和图标,因为没有ActionBar.Tab做保存.

public class CompatTabEclair extends CompatTab {
    // Store these properties in the instance,
    // as there is no ActionBar.Tab object.
    private CharSequence mText;
    ...

    public CompatTab setText(int resId) {
        // Our older implementation simply stores this
        // information in the object instance.
        mText = mActivity.getResources().getText(resId);
        return this;
    }

    ...
    // Do the same for other properties (icon, callback, etc.)
}

TabHelperEclair实现用了TabHost 来创建 TabHost.TabSpec对象和指示器

public class TabHelperEclair extends TabHelper {
    private TabHost mTabHost;
    ...

    protected void setUp() {
        if (mTabHost == null) {
            // Our activity layout for pre-Honeycomb devices
            // must contain a TabHost.
            mTabHost = (TabHost) mActivity.findViewById(
                    android.R.id.tabhost);
            mTabHost.setup();
        }
    }

    public void addTab(CompatTab tab) {
        ...
        TabSpec spec = mTabHost
                .newTabSpec(tag)
                .setIndicator(tab.getText()); // And optional icon
        ...
        mTabHost.addTab(spec);
    }

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

现在,你有了两个 CompatTab and TabHelper的实现,一个运行在是Android 3.0以上版本,用了新的API,另一个工作在Android 2.0以上版本,用了旧的API.下一节讨论在你的应用中使用这些实现.