Android笔记04-选项卡
注意
- 选项卡要跳转几个页面,就得写几个xml布局文件
- 要用TapHost布局管理器
- 要添加TabWidget和TabContent
在xml中的设置
在activity_main.xml中的设置
添加TabHost,TabWidget,TabContent等组件,其中,TabContent由frameLayout来完成。
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id = "@android:id/tabhost" //一定要设置id,而且是Android为我们预定好的id形式
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.xxxxxxx.MainActivity" //xxxxxx为自定义内容
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientaion="vertical" //设置垂直布局 >
<TabWidget
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id = "@android:id/tabs" //同样要设置id></TabWidget>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id = "@android:id/tabcontent" //同样要设置id></FrameLayout>
></TabHost>
在选项卡跳转的页面xml中设置
有几个跳转终点页面,就得写几个xml,并且存放在res下的layout文件中,后缀为.xml
这里就比较自由了,随便你想设置怎么样的页面布局。
在java文件中的设置
思路
- 先在xml文件中找到TabHost组件,并且用
tabHost.setup(); 方法来初始化, - 再实例化一个布局填充器,并用
inflate(); 的方法给把标签页布局填入。 - 再用
addTab(); 方法给TabHost添加标签页
protected void onCreate(Bundle savedInstanceState){
protected void onCreate(savedInstanceState){
setContentView(R.layout.activity_main);
TabHost.setup();
LayoutInflater inflater = LayoutInflater.from(this);
inflater.inflate(R.layout.tabl,tabHost.getTabContentView());
inflater.inflate(R.layout.tab2,tabHost.getTabContentView());
tabHost.addTab(tabHost.newTabSpace("tab1").setIndicator("标签页1").setContent(R.id.left));
tabHost.addTab(tabHost.newTabSpace("tab2").setIndicator("标签页2").setContent(R.id.right));
}
}
如下图显示,tabHost.addTab(); 方法添加的就是红色表框的标签页,存放这两个标签页的横栏空间是利用inflater.inflate(); 方法把它们的布局文件填充到LayoutInflater布局填充器中的。点击两个标签,可以转换不同的页面。
|