4

下面是代碼來設置tabhost,但是有兩個問題爲什麼Tab主機不能在android中顯示圖標?

  1. 文本將進入下一行,如果實在是太長了,我可以減少 大小,它強制單行?
  2. 所有圖標不顯示,即使我相信圖片src是正確的

    public class MainActivity extends FragmentActivity { 
    
        @Override 
        protected void onCreate(Bundle savedInstanceState) { 
         super.onCreate(savedInstanceState); 
         setContentView(R.layout.activity_main); 
    
         FragmentTabHost tabHost = (FragmentTabHost)findViewById(android.R.id.tabhost); 
    
         tabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent); 
         tabHost.addTab(tabHost.newTabSpec("restaurant").setIndicator("Restaurant",getResources().getDrawable(R.drawable.food)),PlaceList.class, null); 
         tabHost.addTab(tabHost.newTabSpec("attraction").setIndicator("Attraction",getResources().getDrawable(R.drawable.view)), PlaceList.class, null); 
         tabHost.addTab(tabHost.newTabSpec("map").setIndicator("Map",getResources().getDrawable(R.drawable.map)),Map.class,null); 
         tabHost.addTab(tabHost.newTabSpec("planner").setIndicator("Planner",getResources().getDrawable(R.drawable.plan)),Planner.class, null); 
        } 
    } 
    
+0

感謝編輯 – user782104

+0

嘗試不帶參數調用'tabHost.setup()'。 – agamov

+0

拋出異常:必須調用帶有Context和FragmentManager的setup() – user782104

回答

5

當調用TabSpec.setIndicator,將Drawablewill only be visible if the label is null or empty.傳遞至於確保了TextView被限制爲單行,你可以循環TabWidget.getTabCount,然後撥打TabWidget.getChildTabViewAtView.findViewById得到TextView用於設置標題。之後,只需致電TextView.setSingleLine即可。

final TabWidget tabWidget = tabHost.getTabWidget(); 
    for (int i = 0; i < tabWidget.getTabCount(); i++) { 
     final View tab = tabWidget.getChildTabViewAt(i); 
     final TextView title = (TextView) tab.findViewById(android.R.id.title); 
     title.setSingleLine(); 
    } 

或者,您可以通過爲Widget.TabWidget創建樣式來擴充自己的選項卡布局。

<style name="Your.TabWidget" parent="@android:style/Widget.TabWidget"> 
    <item name="android:tabLayout">@layout/your_tab_layout</item> 
</style> 

在你父母的主題創建一個新的itemandroid:tabWidgetStyle應用它。

+0

謝謝。所以保持標籤和圖標的唯一方法是創建自定義選項卡布局? – user782104

+1

你可以調用'TextView.setCompoundDrawablesWithIntrinsicBounds'。 – adneal

+1

@ user782104如果您對答案感到滿意,請將其標記爲已接受嗎? – adneal

相關問題