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

相关问题