我試圖在佈局中製作標籤。我發現使用TabWidget
,TabHost
大量的實例和教程,但它們都涉及下列之一:如何使用XML完全製作帶有製表符的佈局?
- Java代碼在活動
- 每個標籤單獨活動
- 每個獨立片段標籤
標籤內的內容是靜態的,所以我應該能夠將所有內容都包含在純XML中。
無論如何要做到這一點?
我試圖在佈局中製作標籤。我發現使用TabWidget
,TabHost
大量的實例和教程,但它們都涉及下列之一:如何使用XML完全製作帶有製表符的佈局?
標籤內的內容是靜態的,所以我應該能夠將所有內容都包含在純XML中。
無論如何要做到這一點?
簡單的答案,沒有。您必須使用Java代碼設置您的TabHost
並創建您的選項卡。您可以在不使用片段的情況下擁有標籤的靜態佈局,但仍需要Java中的設置。
如果您不在代碼中執行此設置,您的TabWidget
將不知道哪個佈局對應哪個選項卡,並且無法運行。你將不得不寫一些代碼。
儘管這樣做的代碼非常簡單。
的XML(放在版面裏,你想讓它):
<TabHost android:id="@+id/tab_host"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TabWidget android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/tab_one_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="@+id/tab_two_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</FrameLayout>
</LinearLayout>
</TabHost>
的Java代碼(放在任何你設置你的佈局):
TabHost host = (TabHost)findViewById(R.id.tab_host);
host.setup();
TabSpec spec = host.newTabSpec("Tab One");
spec.setContent(R.id.tab_one_container);
spec.setIndicator("Tab One");
host.addTab(spec);
spec = host.newTabSpec("Tab Two");
spec.setContent(R.id.tab_two_container);
spec.setIndicator("Tab Two");
host.addTab(spec);
你將不得不在一些點上有一些代碼--xml不會知道如何切換時,單擊一個選項卡,當發生這種情況時該怎麼辦。你可以避免像活動/片段一樣重的東西,但它不會是無碼的。 – 2013-03-14 20:52:06