TabHost标签控件

   如果在屏幕上要放置很多的控件,可能一个屏放不下,除了使用滚动视图的方式外,还可以使用标签控件对屏幕进行分页显示,当单击标签控件的不同标签时,会显示当前标签的内容,在android系统中一个标签可以是一个View或者是Activity。
   TabHost是标签控件的核心类,也是一个标签的集合,每一个标签是TabHost.TabSpec对象。通过TabHost类的addTab的方法添加多个TabHost.TabSpec对象。
  下面是实列:
  在main.xml文件中:
 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent" >
 5     <TextView
 6         android:id="@+id/textview1"
 7         android:layout_width="fill_parent"
 8         android:layout_height="fill_parent"
 9         android:background="#FF0000" />
10     <TextView
11         android:id="@+id/textview2"
12         android:layout_width="fill_parent"
13         android:layout_height="fill_parent"
14         android:background="#00FF00" />  
15     <TextView
16         android:id="@+id/textview3"
17         android:layout_width="fill_parent"
18         android:layout_height="fill_parent"
19         android:background="#0000FF" />
20 </RelativeLayout>

在.java 文件中:

 1 public class MainActivity extends TabActivity {   //注意,这里继承TabActivity,具体详细介绍查手册
 2 
 3     private TabHost host;
 4     @SuppressWarnings("deprecation")
 5     @Override
 6     protected void onCreate(Bundle savedInstanceState) {
 7         super.onCreate(savedInstanceState);
 8     //    setContentView(R.layout.main);
 9         
10         host = getTabHost();
11         LayoutInflater.from(this).inflate(R.layout.main,host.getTabContentView() , true);
12         host.addTab(host.newTabSpec("tab1").setIndicator("red", getResources().getDrawable(android.R.drawable.ic_input_add)).setContent(R.id.textview1));
13         host.addTab(host.newTabSpec("tab2").setIndicator("green", getResources().getDrawable(android.R.drawable.ic_input_delete)).setContent(R.id.textview2));
14         host.addTab(host.newTabSpec("tab3").setIndicator("blue", getResources().getDrawable(android.R.drawable.ic_input_get)).setContent(R.id.textview3));
15         host.setOnTabChangedListener(new OnTabChangeListener() {
16             
17             @Override
18             public void onTabChanged(String tabId) {
19                 // TODO 自动生成的方法存根
20                 Toast.makeText(MainActivity.this, "tabId"+tabId, Toast.LENGTH_LONG).show();
21             }
22         });
23         
24     }
25 
26     @Override
27     public boolean onCreateOptionsMenu(Menu menu) {
28         // Inflate the menu; this adds items to the action bar if it is present.
29         getMenuInflater().inflate(R.menu.main, menu);
30         return true;
31     }
32 
33 }

运行结果:

史上最全的Android的Tab与TabHost讲解
http://www.eoeandroid.com/thread-1035-1-1.html
原文地址:https://www.cnblogs.com/SoulCode/p/5399872.html