W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
編寫:spencer198711 - 原文:http://developer.android.com/training/backward-compatible-ui/using-component.html
既然對TabHelper
和CompatTab
你已經(jīng)有了兩種具體實現(xiàn),一個為Android 3.0和其后版本,一個為Android 3.0之前的版本。現(xiàn)在,該使用這些實現(xiàn)做些事情了。這一課討論了創(chuàng)建在這兩種實現(xiàn)之前切換的邏輯,創(chuàng)建能夠感知版本的界面布局,最終使用我們創(chuàng)建的后向兼容的UI組件。
TabHelper
抽象類基于當前設(shè)備的平臺版本,是用來創(chuàng)建適當版本的TabHelper
和CompatTab
實例的工廠類:
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);
}
}
...
}
下一步是提供能夠支持兩種tab實現(xiàn)的Activity界面布局。對于老的實現(xiàn)(TabHelperEclair),你需要確保你的界面布局包含TabWidget和TabHost,同時存在一個包含tab內(nèi)容的布局容器。
res/layout/main.xml:
<!-- This layout is for API level 5-10 only. -->
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
</TabHost>
對于TabHelperHoneycomb
的實現(xiàn),你唯一要做的就是一個包含tab內(nèi)容的FrameLayout,這是由于ActionBar已經(jīng)提供了tab相關(guān)的頁面。
res/layout-v11/main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
在運行的時候,Android將會根據(jù)平臺版本去決定使用哪個版本的main.xml
布局文件。這根上一節(jié)中選擇哪一個版本的TabHelper
所展示的邏輯是相同的。
在Activity的onCreate())方法中,你可以獲得一個TabHelper
對象,并且使用以下代碼添加tabs:
@Override
public 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);
}
當運行這個應(yīng)用的時候,代碼會自動顯示對應(yīng)的界面布局和實例化對應(yīng)的TabHelperHoneycomb
或TabHelperEclair
對象,而實際使用的類對于Actvity來說是不透明的,因為它們擁有共同的TabHelper
接口。
以下是這種實現(xiàn)運行在Android 2.3和Android 4.0上的界面截圖:
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: