TabHost广泛运用于android程序中,在程序中运用TabHost,解决了手机屏幕小,显示内容少的问题,如系统自带的拨号程序,就用了TabHost.
分为拨号、通话纪录、联系人、收藏几个Tab。
先看今天学习的例子的最终效果。
分为三个标签Tab1、Tab2、Tab3。
TabHost与普通的Activity有点区别,主程序继承TabActivity,而不是Activity。所以,在新建项目时Creat Activity不要勾选,因为这里创建的是普通的Activity.
建好项目后,新建一个Class,SuperClass选择android.app.TabActivity,然后将这个TabActivity加入AndroidMainifest.xml,用以下代码:
1 2 3 4 5 6 7 | <activity android:name=".main" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> |
这段代码放在application标签内,第一行的main要和刚刚建立的TabActivity名对应。
然后就是布局XML,这里用到FrameLayout,框架布局,把三个Tab的布局放在一个FrameLayout里,用id区分。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <!--tab1的布局 --> <LinearLayout android:id="@+id/tab1" android:layout_width="fill_parent" android:layout_height="fill_parent" androidrientation="vertical" > <EditText android:id="@+id/widget34" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="EditText" android:textSize="18sp"> </EditText> <Button android:id="@+id/widget30" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button"> </Button> </LinearLayout> <!--tab2的布局 --> <LinearLayout android:id="@+id/tab2" android:layout_width="fill_parent" android:layout_height="fill_parent" androidrientation="vertical" > <AnalogClock android:id="@+id/widget36" android:layout_width="wrap_content" android:layout_height="wrap_content"> </AnalogClock> </LinearLayout> <!--tab3的布局 --> <LinearLayout android:id="@+id/tab3" android:layout_width="fill_parent" android:layout_height="fill_parent" androidrientation="vertical"> <RadioGroup android:id="@+id/widget43" android:layout_width="166px" android:layout_height="98px" androidrientation="vertical"> <RadioButton android:id="@+id/widget44" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="RadioButton"> </RadioButton> <RadioButton android:id="@+id/widget45" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="RadioButton"> </RadioButton> </RadioGroup> </LinearLayout> </FrameLayout> |
程序代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |