这适用于除 Jelly Bean 之外的所有操作系统。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("Tab1").setIndicator("One"),
Tab1.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Tab2").setIndicator("Two"),
Tab2.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Tab3").setIndicator("Three"),
Tab3.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Tab4").setIndicator("Four"),
Tab4.class, null);
TabWidget mTabWidget = mTabHost.getTabWidget();
mTabWidget.setStripEnabled(false);
for(int i=0; i < mTabWidget.getChildCount(); i++){
View v = mTabWidget.getChildAt(i);
v.setBackgroundResource(R.drawable.tab_selector);
}
}
布局:
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget
android:id="@android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="@+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
背景资源:
`<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Active tab -->
<item android:state_selected="true" android:state_focused="false"
android:state_pressed="false" android:drawable="@android:color/white" />
<!-- Inactive tab -->
<item android:state_selected="false" android:state_focused="false"
android:state_pressed="false" android:drawable="@android:color/black" />
<!-- Pressed tab -->
<item android:state_pressed="true" android:drawable="@android:color/transparent" />
<!-- Selected tab -->
<item android:state_focused="true" android:state_selected="true"
android:state_pressed="false" android:drawable="@android:color/transparent" />
`
这里没有什么疯狂的......那么为什么果冻豆显示只有白色背景而没有文本的活动选项卡?非活动选项卡显示正确的颜色和文本。