Android——TabWidget(切换卡)
16lz
2021-01-23
【注】
1、TabHost的id必须@android:id/tabhost;必须有一个id为@android:id/tabs的TabWidget;必须有一个id为@android:id/tabcontent的FrameLayout。
2、在addTab方法中必须有setIndicator。
3、想要将切换卡放到屏幕下面,需要使用RelativeLayout布局
【介绍】切换卡(TabWidget)是一种相对复杂的继承自LinearLayout的布局管理器,通过多个标签来切换显示不同的内容,一个TabWidget主要由一个TabHost来存放多个Tab标签容器,再在Tab容器中加入其它控件,通过addTab方法添加新的Tab。
【属性】
1、包含线性布局的属性,如orientation和gravity
2、自己的属性,如divider,tabStripEnabled,tabStripLeft,tabStripRight
【示例】
[layout/.xml]
<?xml version="1.0"encoding="utf-8"?><TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@android:id/tabhost"> <LinearLayout android:layout_width="fill_parent" android:orientation="vertical" android:layout_height="fill_parent"> <TabWidget android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@android:id/tabs"></TabWidget> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@android:id/tabcontent"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/textview1" android:text="这是第一个tab页"/> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/textview2" android:text="这是第二个tab页"/> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/textview3" android:text="这是第三个tab页"/> </FrameLayout> </LinearLayout> </TabHost><span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span>
[.java]
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TabHost th=(TabHost) findViewById(android.R.id.tabhost); th.setup(); th.addTab(th.newTabSpec("tab1").setIndicator("First").setContent(R.id.textview1)); th.addTab(th.newTabSpec("tab2").setIndicator("Second").setContent(R.id.textview2)); th.addTab(th.newTabSpec("tab3").setIndicator("Third").setContent(R.id.textview3)); }}
【运行】