用较早版本的APIs实现抽象类

原文链接:http://android.eoe.cn/topic/android_sdk

 

用较早版本的APIs实现抽象类

这节课程我们讨论如何创建一个实现类,即能对应新版本的API,又能够保持对老版本API的支持。

寻找一个替代的解决方案


为了保持向后兼容,我们需要用老版本平台的UI框架特性来实现新本版的UI框架特性,这是一件非常具有挑战性的任务。在很多情况下,我们是完全可以做到这一点的,请看下边的例子:

一般情况下,我们无法找到一个完美的方案,可以把新UI组件的完全的移植到旧版本的设备上。在这个问题上我们应该多考虑一下用户体验,使用老版本设备的用户可能对新版本的设计模式并不熟悉。因此我们在实现的时候要考虑相同的功能实现尽量用用户熟悉的方式来实现。很多情况下我们不必过于担心这个问题,如果这个新的UI组件在应用程序的环境中设计的比较优秀(比如:'''Action Bar''')或者交互模式非常简单和直观的(比如:'''Swip Views'''应用 ViewPager

用较早版本API实现Tabs


我们可以用TabWidgetTabHost 我们也可以用horizontally laid-out Button部件来实现'''ActionBar'''标签。因为我们使用了Android 2.0 (Eclair)以下的APIs,所以我们的实现类名字叫做TabHelperEclair和CompatTabEclair:

图1:Eclair实现tabs的类图

实现CompatTabEclair时需要在变量中保存tab的属性,比如:text、icon等。因为我们已经没有现成的ActionBar.Tab可以帮助来处理这些属性了。

 1

 2

 3

 4

 5

 6

 7

 8

 9

10

11

12

13

14

15

16
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 indicators:

 1

 2

 3

 4

 5

 6

 7

 8

 9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26
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的两个实现类了,一个用在Android 3.0或者更新的版本的APIs中,一个用在Android 2.0或更新版本的APIs中,下节课我们将讨论如何在我们的应用中使用这样两个实现类。

 

你可能感兴趣的:(api)