TabHost默认情况下是显示在屏幕顶部,但是很多情况下我们希望它显示在底部,ok,直接上代码
第一步:首先是布局文件
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
</LinearLayout>
</TabHost>
第二步:在Activity中使用TabHost,注意,我创建了三个activity用来跳转,每个activity显示一张图片,这里只给出使用TabHost的activity代码
剩下的三个测试用的activity,大家自由发挥了。
package com.front.tabdemo;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
public class MainActivity extends TabActivity {
private TabHost host;
private TabWidget widget;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
host = this.getTabHost();
Intent it_one = new Intent(this, activity_one.class);
TabHost.TabSpec one_spec = host.newTabSpec("第一张");
one_spec.setContent(it_one);
one_spec.setIndicator("第一张");
host.addTab(one_spec);
Intent it_two = new Intent(this, activity_two.class);
TabHost.TabSpec two_spec = host.newTabSpec("第二张");
two_spec.setContent(it_two);
two_spec.setIndicator("第二张");
host.addTab(two_spec);
Intent it_three = new Intent(this, activity_three.class);
TabHost.TabSpec three_spec = host.newTabSpec("第三张");
three_spec.setContent(it_three);
three_spec.setIndicator("第三张");
host.addTab(three_spec);
widget = host.getTabWidget();
// 初始化各个标签的背景
setTabBackground();
// 给host添加标签改变事件,点击相应的标签时改变其背景
host.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
setTabBackground();
}
});
}
public void setTabBackground() {
for (int i = 0; i < widget.getChildCount(); i++) {
View view = widget.getChildAt(i);
if (host.getCurrentTab() == i) {
view.setBackgroundResource(R.drawable.number_bg_pressed);
} else {
view.setBackgroundResource(R.drawable.number_bg);
}
}
}
}
ok,这样显示在底部的TabHost就完成了,效果图如下: