Android -- TabHost
TabHost 也就相当于Windows下的选项框
有两种实现方式
1. 继承TabActivity (已经废弃):从TabActivity中用getTabHost()方法获取TabHost
2. 在布局文件中定义TabHost,但是TabWidget的id必须是@android:id/tabs,FrameLayout的id必须是@android:id/tabcontent.
主要介绍第二种方法的使用
Layout
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/hometabs" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <!-- 此Id不可改变 --> <TabHost android:id="@+id/tabhost" android:layout_width="fill_parent" android:layout_height="wrap_content" > <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" android:orientation="horizontal" > </TabWidget> <!-- 此Id不可改变 --> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/text" android:layout_width="match_parent" android:layout_height="match_parent" android:text="第一个选项框" /> <TextView android:id="@+id/photo" android:layout_width="match_parent" android:layout_height="match_parent" android:text="第二个选项框" /> <TextView android:id="@+id/video" android:layout_width="match_parent" android:layout_height="match_parent" android:text="第三个选项框" /> </FrameLayout> </LinearLayout> </TabHost> </LinearLayout>
MainActivity
@ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ); setContentView ( R.layout.activity_main ); TabHost tabHost = ( TabHost ) findViewById ( R.id.tabhost ); /** * 如何继承TabActivity 则不需要回调该函数 */ tabHost.setup ( ); /** * 增加标题头文件 ,相当于选项框 */ tabHost.addTab ( tabHost.newTabSpec ( "tab1" ) .setIndicator ( "文本新闻" , getResources ( ).getDrawable ( R.drawable.ic_launcher ) ) .setContent ( R.id.text ) ); //添加选项框二 tabHost.addTab ( tabHost.newTabSpec ( "tab2" ) .setIndicator ( "图片新闻" , getResources ( ).getDrawable ( R.drawable.ic_launcher ) ) .setContent ( R.id.photo ) ); //添加选项框三 tabHost.addTab ( tabHost.newTabSpec ( "tab3" ) .setIndicator ( "视频新闻" , getResources ( ).getDrawable ( R.drawable.ic_launcher ) ) .setContent ( R.id.video ) ); }