吐槽:本来我以为已经写了,结果没写!!!
①主布局文件(activity_main.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="@+id/tabhost" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TabWidget
android:id="@android:id/tabs"
<!--这里一定要注意,id是不能改的!!! -->
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</TabWidget>
<FrameLayout
android:id="@android:id/tabcontent"
<!--这里一定要注意,id是不能改的!!! -->
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/tv2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="我是二"
android:textSize="50dp"
/>
<Button
android:id="@+id/tv3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="我是三"
android:textSize="50dp"
/>
</FrameLayout>
</LinearLayout>
</TabHost>
②tabhost02.xml(测试不同布局下也能加到同一个tabhost中):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/l1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/ic_launcher" >
</LinearLayout>
③MainActivity.java:
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
TabHost host = (TabHost) findViewById(R.id.tabhost)
host.setup()
LayoutInflater inflater = LayoutInflater.from(this)
inflater.inflate(R.layout.tabhost02, host.getTabContentView())
host.addTab(host.newTabSpec("frist").setIndicator("第一个标签").setContent(R.id.l1))
//注意id为l1的控件在tabhost02.xml中
host.addTab(host.newTabSpec("secound").setIndicator("第二个标签").setContent(R.id.tv2))
host.addTab(host.newTabSpec("third").setIndicator("第三个标签").setContent(R.id.tv3))
}
}
TabHost实现局部局域刷新,需要用到其中的一个重要属性,clearallTabs()方法