安卓高级组件-----选项卡

        选项卡是安卓高级组件中常用到的一种,能够对页面进行俭省,比如我们常用的qq界面,联系人,消息等功能选项页其实是在一个activity里面的,对他们进行切换并没有导致页面的刷新;再如,手机的电话功能包括了联系人,未接电话,已接电话等,他们都是在一个界面中,是在同一个界面的切页进行切换。如果把上述放到不同的界面,似乎使用起来会很累赘。所以本节介绍使用选项卡,制作简单的切页。

解释一下选项卡:

        选型卡功能让新手有点懵,作为新手,大致说说:

如下图,一个整体的选项卡包括数个切页,这个整体是TabHost组件,组件内含一个垂直的线性布局,上部分是切页标题(TabWidget),下部分是帧布局。我们每次通过标题选择切页,都会引起下发的帧布局变化,选择的帧会出现在最上面,这就是选项卡的原理。在代码方面,整体称为TabHost,下方的标题和帧组成TabSpec,增减切页其实增减的是TabSpec。

1.添加基本布局组件(eclipse拖拽进来会多出几个线性布局,可以删除,因为那是帧布局内部的布局,可以不用)

    <TabHost                                                           //此处是TabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout                                                  //垂直的线性布局决定了上面是标题,下面是帧
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <TabWidget                                                //标题部分
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >
            </TabWidget>

            <FrameLayout                                             //切换帧
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >
            </FrameLayout>
        </LinearLayout>
    </TabHost>

2.获取TabHost并且初始化

        private TabHost tabHost;
        tabHost =(TabHost)findViewById(android.R.id.tabhost);
        tabHost.setup();

3.创建三个布局文件,这三个布局文件是加给选项卡的帧容器的,这样就能实现内容切换

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/n"
    android:src="@drawable/nature"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    

</ImageView>

4.给TabHost添加切页,包括标题和帧。主活动里面添加布局是通过setContentView()实现初始化,选项卡的添加是在已知布局里面添加内容,不是布局的初始化,所以我们需要通过布局填充才能实现将定义的三个布局添加到帧中去。

        LayoutInflater inflater = LayoutInflater.from(this);             //获得布局填充器
        
        inflater.inflate(R.layout.lay1, tabHost.getTabContentView());        
        inflater.inflate(R.layout.lay2, tabHost.getTabContentView());
        inflater.inflate(R.layout.lay3, tabHost.getTabContentView());
        
        tabHost.addTab(tabHost.newTabSpec("tab01").setIndicator("山水").setContent(R.id.n));
        tabHost.addTab(tabHost.newTabSpec("tab02").setIndicator("风景").setContent(R.id.s));
        tabHost.addTab(tabHost.newTabSpec("tab03").setIndicator("启动").setContent(R.id.i));

反思:选项卡还是比较简单实现的,唯一用到一个新手难以理解的布局填充,这还是多看看相关的文章。

请留言,帮助改进!

 

posted @ 2017-03-02 17:49  爱潜水的猪  阅读(396)  评论(0编辑  收藏  举报