安卓控件使用系列29:TabHost卡片的使用方法2不继承TabActivity、TabHost控件、一个布局文件

时间:2021-07-08 19:30:21

这里介绍一下使用TabHost的第二种方法,特征是不继承TabActivity、并使用TabHost控件、只使用一个布局文件。

这个例子实现的是点击不同的卡片进入不同的界面。

整体思路:在xml文件中添加一个Button控件,添加一个TabHost控件,在这个TabHost控件再添加一个LinearLayout布局,这个LinearLayout布局布局中放置一个TabWidget控件和一个FrameLayout布局,这个FrameLayout布局放入三个LinearLayout布局,这三个布局的宽和高都为填充父窗口;在活动中初始化这个TabHost容器,并将三个LinearLayout布局添加到TabHost控件上。这样就实现了在手机屏幕上上面一个Button按钮,下面是三个菜单项,点击不同的菜单项,进入不同的页面。

activity_main.xml文件:

<Button 
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
/>
<TabHost
android:id="@+id/tabhost"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<!-- 这里的TabWidget和FrameLayout要使用@android来命名标签,否则会报错-->
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
></TabWidget>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<!-- 第一个tab布局 -->
<LinearLayout
android:id="@+id/tab1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="张惠妹"
/>
</LinearLayout>
<!-- 第二个tab布局 -->
<LinearLayout
android:id="@+id/tab2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/textview2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="罗志祥"
/>
</LinearLayout>
<!-- 第三个tab布局 -->
<LinearLayout
android:id="@+id/tab3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/textview3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="吴建豪"
/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>

MainActivity.java文件:

        TabHost th=(TabHost)findViewById(R.id.tabhost);
th.setup();//初始化TabHost容器

//在TabHost创建标签,然后设置:标题、图标、标题页布局
th.addTab(th.newTabSpec("tab1").setIndicator("标签1",getResources().getDrawable(R.drawable.ic_launcher)).setContent(R.id.tab1));
th.addTab(th.newTabSpec("tab2").setIndicator("标签2",null).setContent(R.id.tab2));
th.addTab(th.newTabSpec("tab3").setIndicator("标签3",null).setContent(R.id.tab3));