您好,欢迎访问一九零五行业门户网

Android UI控件系列:TabWidget(切换卡)

tab选项卡类似与电话本的界面,通过多个标签切换不同的内容,要实现这个效果,首先要知道tabhost,它是一个用来存放多个tab标签的容器,每一个tab都可以对应自己的布局,比如,电话本中的tab布局就是一个线性布局
要使用tabhost,首先要通过gettabhost方法获取tabhost的对象,然后通过addtab方法来向tabhost中添加tab,当然每个tab在切换时都会产生一个事件,要捕捉这个事件,需要设置tabactivity的事件监听setontabchangedlistener
下面是个小例子:
tabtest.java
package org.hualang.tab; import android.app.activity; import android.app.tabactivity; import android.graphics.color; import android.os.bundle; import android.widget.tabhost; import android.widget.toast; import android.widget.tabhost.ontabchangelistener; public class tabtest extends tabactivity { /** called when the activity is first created. */ tabhost tabhost; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); //取得tabhost对象 tabhost = gettabhost(); //为tabhost添加标签 //新建一个newtabspec(newtabspec) //设置其标签和图标(setindicator) //设置内容(setcontent) tabhost.addtab(tabhost.newtabspec("tab1") .setindicator("tab 1",getresources().getdrawable(r.drawable.img1)) .setcontent(r.id.text1)); tabhost.addtab(tabhost.newtabspec("tab2") .setindicator("tab 2",getresources().getdrawable(r.drawable.img2)) .setcontent(r.id.text2)); tabhost.addtab(tabhost.newtabspec("tab3") .setindicator("tab 3",getresources().getdrawable(r.drawable.img3)) .setcontent(r.id.text3)); //设置tabhost的背景颜色 //tabhost.setbackgroundcolor(color.argb(150,22,70,150)); //设置tabhost的背景图片资源 tabhost.setbackgroundresource(r.drawable.bg0); //设置当前显示哪个标签 tabhost.setcurrenttab(0); //标签切换事件处理,setontabchangedlistener tabhost.setontabchangedlistener(new ontabchangelistener() { public void ontabchanged(string tabid) { toast toast=toast.maketext(getapplicationcontext(), "现在是"+tabid+"标签", toast.length_short); toast.show(); } }); } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <tabhost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <linearlayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <tabwidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <framelayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent"> <textview android:id="@+id/text1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="选项卡1" /> <textview android:id="@+id/text2" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="选项卡2" /> <textview android:id="@+id/text3" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="选项卡3" /> </framelayout> </linearlayout> </tabhost>
运行效果如下:
以上就是android ui控件系列:tabwidget(切换卡)的内容。
其它类似信息

推荐信息