< FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
FrameLayout >
TabHost >
说明: 在应用XML布局文件添加选项卡时,必须使用系统的id来为各组件指定id属性,否则将出现异常。
(2)编写各标签页中要显示内容对应的XML布局文件。例如,编写一个XML布局文件,名称为tab1.xml,用于指定第一个标签页中要显示的内容,具体代码如下:
android:id="@+id/LinearLayout01"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="简约但不简单"/>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="风铃草"/>
说明: 在本实例中,除了需要编写名称为tab1.xml的布局文件外,还需要编写名称为tab2.xml的布局文件,用于指定第二个标签页中要显示的内容。
(3)在Activity中,获取并初始化TabHost组件,关键代码如下:
private TabHost tabHost; //声明TabHost组件的对象
tabHost=(TabHost)findViewById(android.R.id.tabhost); //获取TabHost对象
tabHost.setup(); //初始化TabHost组件
(4)为TabHost对象添加标签页,这里共添加了两个标签页,一个用于模拟显示未接来电,另一个用于模拟显示已接来电,关键代码如下:
LayoutInflater inflater = LayoutInflater.from(this); //声明并实例化一个LayoutInflater对象
inflater.inflate(R.layout.tab1, tabHost.getTabContentView());
inflater.inflate(R.layout.tab2, tabHost.getTabContentView());
tabHost.addTab(tabHost.newTabSpec("tab01")
.setIndicator("未接来电")
.setContent(R.id.LinearLayout01)); //添加第一个标签页
tabHost.addTab(tabHost.newTabSpec("tab02")
.setIndicator("已接来电")
.setContent(R.id.FrameLayout02)); //添加第二个标签页
运行本实例,将显示如图4.6所示的运行结果。
图4.6 在屏幕中添加选项卡
4.1.5 图像切换器
图像切换器(ImageSwitcher),用于实现类似于Windows操作系统下的“Windows照片查看器”中的上一张、下一张切换图片的功能。在使用ImageSwitcher时,必须实现ViewSwitcher.ViewFactory接口,并通过makeView()方法来创建用于显示图片的ImageView。makeView()方法将返回一个显示图片的ImageView。在使用图像切换器时,还有一个方法非常重要,那就是setImageResource()方法,该方法用于指定要在ImageSwitcher中显示的图片资源。
下面通过一个具体的实例来说明图像切换器的用法。
例4.6 在Eclipse中创建Android项目,名称为4.6,实现类似于Windows照片查看器的简单的图片查看器。(实例位置:光盘\TM\sl\4\4.6)
(1)修改新建项目的res\layout目录下的布局文件main.xml,将默认添加的垂直线性布局修改为水平线性布局,并将TextView组件删除,然后添加两个按钮和一个图像切换器ImageSwitcher,并设置图像切换器的布局方式为居中显示。修改后的代码如下:
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/llayout"
android:gravity="center" >
android:text="上一张"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
< ImageSwitcher
android:id="@+id/imageSwitcher1"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
android:text="下一张"
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
(2)在主活动中,首先声明并初始化一个保存要显示图像id的数组,然后声明一个保存当前显示图像索引的变量,再声明一个图像切换器的对象,具体代码如下: