2013-03-14 25 views
9

我試圖在佈局中製作標籤。我發現使用TabWidgetTabHost大量的實例和教程,但它們都涉及下列之一:如何使用XML完全製作帶有製表符的佈局?

  • Java代碼在活動
  • 每個標籤單獨活動
  • 每個獨立片段標籤

標籤內的內容是靜態的,所以我應該能夠將所有內容都包含在純XML中。

無論如何要做到這一點?

+3

你將不得不在一些點上有一些代碼--xml不會知道如何切換時,單擊一個選項卡,當發生這種情況時該怎麼辦。你可以避免像活動/片段一樣重的東西,但它不會是無碼的。 – 2013-03-14 20:52:06

回答

12

簡單的答案,沒有。您必須使用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); 
+0

那種糟透了。爲什麼不能在標籤中引用佈局的ID來連接它們? 我不介意寫代碼,但我覺得不得不把代碼中的鏈接放在不合適的地方。 – erwan 2013-03-14 20:59:26

+1

你不能這樣做,因爲Google沒有將它寫入SDK。我希望我對你有更好的答案,但是當你與別人的框架一起工作時,你就會受到他們的限制。這恰好是這些限制之一。 – MCeley 2013-03-14 21:03:41