android TabHost导航切换实现方式

下面是利用TabHost实现的Tab选项卡

在写TabHost布局文件时我们需要注意id格式如下

TabHost的id必须为 android:id="@android:id/tabhost"

FrameLayout的id必须为 android:id="@android:id/tabcontent"

TabWidget的id必须为 android:id="@android:id/tabs"

FrameLayout包含了页面集(注意FrameLayout框架布局是最简单的布局形式。所有添加到这个布局中的视图都以层叠的方式显示)

TabWidget:代表选项卡的标签条

newTabSpec(String str):创建一个选项卡

tabHost.addTab(newTabSpec)代表把创建的tab页放到tab标签里面进行显示

以下代码是创建了一个tab页面
TabSpec tabs1 = th.newTabSpec("tab1").setIndicator("已播电话").setContent(intent = new Intent(this,Tab1.class));
打个标记 设置标题设置显示的内容


核心代码如下:

package com.example.fragmenttest;


import android.os.Bundle;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;


public class MainActivity extends TabActivity {


private TabHost th;
private Intent intent;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabmain);
initView();
}
public void initView(){
th = getTabHost();//获取TabHost对象
//创建一个Tab页面
TabSpec tabs1 = th.newTabSpec("tab1").setIndicator("已播电话").setContent(intent = new Intent(this,Tab1.class));
//将Tab页面加入到tab标签显示在界面中
th.addTab(tabs1);
//创建第二个Tab页面
TabSpec tabs2 = th.newTabSpec("tab2").setIndicator("已播电话").setContent(intent = new Intent(this,Tab2.class));
//将Tab页面加入到tab标签显示在界面中
th.addTab(tabs2);
//创建第三个Tab页面
TabSpec tabs3 = th.newTabSpec("tab3").setIndicator("已播电话").setContent(intent = new Intent(this,Tab3.class));
th.addTab(tabs3);
//将Tab页面加入到tab标签显示在界面中

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


}
随后我们再看看布局文件(注意id格式!)

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
   
    >
    
    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        >
        
        <FrameLayout 
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            >
            
        </FrameLayout>
        <TabWidget 
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />
    </LinearLayout>

</TabHost>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值