Android笔记04-选项卡

本文介绍如何在Android应用中实现选项卡功能,包括使用TabHost、TabWidget和TabContent组件进行布局设计,以及通过Java代码设置TabHost并实现页面跳转。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android笔记04-选项卡

注意

  1. 选项卡要跳转几个页面,就得写几个xml布局文件
  2. 要用TapHost布局管理器
  3. 要添加TabWidget和TabContent

在这里插入图片描述

在xml中的设置

在activity_main.xml中的设置

添加TabHost,TabWidget,TabContent等组件,其中,TabContent由frameLayout来完成。

<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:tools="http://schemas.android.com/tools"
         android:id = "@android:id/tabhost"  //一定要设置id,而且是Android为我们预定好的id形式
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         tools:context="com.xxxxxxx.MainActivity" //xxxxxx为自定义内容
         <LinearLayout
		 	android:layout_width="match_parent"
        	 android:layout_height="match_parent"
			android:orientaion="vertical" //设置垂直布局 >
			<TabWidget
				android:layout_width="match_parent"
         		android:layout_height="match_parent"
				android:id = "@android:id/tabs" //同样要设置id></TabWidget>

			<FrameLayout
				android:layout_width="match_parent"
         		android:layout_height="match_parent"
				android:id = "@android:id/tabcontent" //同样要设置id></FrameLayout>

></TabHost>
         

在选项卡跳转的页面xml中设置

有几个跳转终点页面,就得写几个xml,并且存放在res下的layout文件中,后缀为.xml

这里就比较自由了,随便你想设置怎么样的页面布局。

在java文件中的设置

思路

  1. 先在xml文件中找到TabHost组件,并且用tabHost.setup(); 方法来初始化,
  2. 再实例化一个布局填充器,并用inflate(); 的方法给把标签页布局填入。
  3. 再用addTab();方法给TabHost添加标签页
protected void onCreate(Bundle savedInstanceState){
    protected void onCreate(savedInstanceState){
        setContentView(R.layout.activity_main); //因为有好几个xml布局文件,因此需要用到哪个就用setContetView方法指定哪个
        TabHost.setup(); //给tab host初始化
        LayoutInflater inflater = LayoutInflater.from(this);  //在添加标签页之前,得先实例化一个LayoutInflater对象,LayoutInflater的意思是布局填充器。
        inflater.inflate(R.layout.tabl,tabHost.getTabContentView()); //把布局tab1填入布局填充器中
        inflater.inflate(R.layout.tab2,tabHost.getTabContentView());  
        tabHost.addTab(tabHost.newTabSpace("tab1").setIndicator("标签页1").setContent(R.id.left));  //给TabHost添加标签页,setIndicator是用来标志这个页面的文字,就是那个转换按钮所显示的文字,setContent是用来设置这个标签的布局管理器的
        tabHost.addTab(tabHost.newTabSpace("tab2").setIndicator("标签页2").setContent(R.id.right));    
        
    }
}

如下图显示,tabHost.addTab();方法添加的就是红色表框的标签页,存放这两个标签页的横栏空间是利用inflater.inflate();方法把它们的布局文件填充到LayoutInflater布局填充器中的。点击两个标签,可以转换不同的页面。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值