Tab选项卡TabView的最基本操作(一)

本文介绍了Android中创建Tab选项卡的基本步骤,包括在布局文件中使用FramLayout列出Tab组件,Activity继承TabActivity,获取TabHost对象以及通过TabHost创建Tab选项。同时,文章提到了如何在创建Tab时同时显示文字和图标。

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

首先简单的创建一个Tab有以下步骤:


1、在布局文件中使用FramLayout列出Tab组件及Tab中的内容组件。
2、Activity要继承TabActivity。
3、调用TabActivity的getTabHost()方法获得TabHost对象。
4、通过TabHost创建Tab选项。



以下是创建过程:

1、创建activity_main.xml文件


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="文本1" />

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="文本2" />

    <TextView
        android:id="@+id/text3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="文本3" />

</FrameLayout>

<FrameLayout>改为<TabHost>也行



2、继承TabActivity

public class MainActivity extends TabActivity

3、获取TabHost对象

TabHost th = getTabHost();

LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main,th.getTabContentView(), true);//设置使用TabHost布局

获取了TabHost对象之后,设置了布局,故不能再调用setContentView设置了


4、通过TabHost创建Tab选项


th.addTab(th.newTabSpec("123").setIndicator("one").setContent(R.id.text1));
th.addTab(th.newTabSpec("456").setIndicator("two").setContent(R.id.text2));
th.addTab(th.newTabSpec("789").setIndicator("three").setContent(R.id.text3));



若想在创建Tab选项的时候同时显示文字和图标,可以这样创建Tab:


th.addTab(th.newTabSpec("123").setIndicator("one",getResources().getDrawable(R.drawable.ic_launcher)).setContent(R.id.text1));


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值