TabHost是整个Tab的容器,包含TabWidget和FrameLayout两个部分,TabWidget是每个Tab的表情,FrameLayout是Tab内容。
实现方式有两种:
1、继承TabActivity
2、继承Activity类
1. TabHost
继承Activity类 TabHost 可自定义id ,用findViewById获取TabHost,并且必须调用setup方法
继承TabActivity TabHost 必须设置android:id为@android:id/tabhost 用 tabhost = getTabHost();方式获取TabHost
2、TabWidget 必须设置android:id为@android:id/tabs
3、FrameLayout 必须设置android:id为@android:id/tabcontent
页面布局有固定的写法
<TabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TabWidget>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="@+id/ll_comment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:id="@+id/ll_thumb_up"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
java代码:
public class MainActivity {
private TabHost tabhost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
tabhost = (TabHost) view.findViewById(android.R.id.tabhost);
tabhost.setup();
TabSpec commentSpec = tabhost.newTabSpec("评论");
commentSpec.setContent(R.id.ll_comment);
commentSpec.setIndicator(createtabWidget(0));
tabhost.addTab(commentSpec);
TabSpec thumbUpSpec = tabhost.newTabSpec("点赞");
thumbUpSpec.setContent(R.id.ll_thumb_up);
thumbUpSpec.setIndicator(createtabWidget(1));
tabhost.addTab(thumbUpSpec);
tabhost.setCurrentTab(0);
updateTab();// 初始化Tab的颜色,和字体的颜色
tabhost.getTabWidget().setStripEnabled(true);
tabhost.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
updateTab();
}
});
}
String[] tabWidgetNames = new String[]{"评论(123)","点赞(10)"};
private View createtabWidget(int pos) {
TextView view = new TextView(getActivity());
view.setText(tabWidgetNames[pos]);
view.setTextColor(Color.GRAY);
view.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
view.setGravity(Gravity.CENTER);
return view;
}
private void updateTab() {
for(int i=0,len = tabhost.getTabWidget().getChildCount();i<len;i++){
TextView textView = (TextView) tabhost.getTabWidget().getChildAt(i);
if(tabhost.getCurrentTab() == i){
textView.setTextColor(Color.RED);
}else{
textView.setTextColor(Color.GRAY);
}
}
}
}