课程内容

  1. 选择一种替代方案
  2. 使用旧的API实现Tabs

动手试试

下载示例代码 TabCompat.zip

这节内容介绍如何在旧版本上模仿新版本的功能。

选择一种替代方案

在旧版本中实现新的UI特性的最具挑战性的任务就是:选择一种旧版本支持的替代方案。有时候使用旧版本中的UI特性可以模仿新的UI特性。例如:

  • Action bars 可以使用一个包含一些图片按钮的水平 LinearLayout来实现。浮动菜单按钮可以通过Menu按钮来模拟。
  • Action bar tabs 同样可以使用包含按钮的水平LinearLayout实现,或者使用 TabWidget UI控件。
  • NumberPicker 和 Switch控件可以分别由Spinner 和 ToggleButton控件来替代。
  • ListPopupWindow 和 PopupMenu 控件可以通过PopupWindow 控件来模拟。 There generally isn’t a one-size-fits-all solution for backporting newer UI components to older devices. Be mindful of the user experience: on older devices, users may not be familiar with newer design patterns and UI components. Give some thought as to how the same functionality can be delivered using familiar elements. In many cases this is less of a concern—if newer UI components are prominent in the application ecosystem (such as the action bar), or where the interaction model is extremely simple and intuitive (such as swipe views using a ViewPager).

使用旧的API实现Tabs

这里我们使用 TabWidget 和TabHost来模拟抽象的API功能。 具体的实现类为 TabHelperEclair 和 CompatTabEclair,名字暗示了该实现只支持Android 2.0 (Eclair)以后的版本。

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

CompatTabEclair 实现中保存了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对象和tab指示器。

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 和 TabHelper实现方式了: 一种用于3.0+系统,一种用于2.0+系统。在下面将接续介绍如何在不同的系统上使用对应的实现。

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