本文共 3099 字,大约阅读时间需要 10 分钟。
Now that you have two implementations of TabHelper
and CompatTab
—one for Android 3.0 and later and one for earlier versions of the platform—it's time to do something with these implementations. This lesson discusses creating the logic for switching between these implementations, creating version-aware layouts, and finally using the backward-compatible UI component. http://blog.csdn.net/sergeycao
The TabHelper
abstract class acts as a for creating version-appropriate TabHelper
and CompatTab
instances, based on the current device's platform version:
public abstract class TabHelper { ... // Usage is TabHelper.createInstance(activity) public static TabHelper createInstance(FragmentActivity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { return new TabHelperHoneycomb(activity); } else { return new TabHelperEclair(activity); } } // Usage is mTabHelper.newTab("tag") public CompatTab newTab(String tag) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { return new CompatTabHoneycomb(mActivity, tag); } else { return new CompatTabEclair(mActivity, tag); } } ...}
The next step is to provide layouts for your activity that can support the two tab implementations. For the older implementation (TabHelperEclair
), you need to ensure that your activity layout contains a and
, along with a container for tab contents:
res/layout/main.xml:
For the TabHelperHoneycomb
implementation, all you need is a
to contain the tab contents, since the tab indicators are provided by the :
res/layout-v11/main.xml:
At runtime, Android will decide which version of the main.xml
layout to inflate depending on the platform version. This is the same logic shown in the previous section to determine which TabHelper
implementation to use.
In your activity's method, you can obtain a
TabHelper
object and add tabs with the following code:
@Overridepublic void onCreate(Bundle savedInstanceState) { setContentView(R.layout.main); TabHelper tabHelper = TabHelper.createInstance(this); tabHelper.setUp(); CompatTab photosTab = tabHelper .newTab("photos") .setText(R.string.tab_photos); tabHelper.addTab(photosTab); CompatTab videosTab = tabHelper .newTab("videos") .setText(R.string.tab_videos); tabHelper.addTab(videosTab);}
When running the application, this code inflates the correct activity layout and instantiates either a TabHelperHoneycomb
or TabHelperEclair
object. The concrete class that's actually used is opaque to the activity, since they share the common TabHelper
interface.
Below are two screenshots of this implementation running on an Android 2.3 and Android 4.0 device.