Tabhost的简单使用

建立主布局文件:

//其中红色为必选项,且注意id的写法

xml version= "1.0" encoding= "utf-8" ?>
<
RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
   
android :layout_width= "match_parent"
   
android :layout_height= "match_parent" >

   <
TabHost
      
android :layout_width= "match_parent"
      
android :layout_height= "wrap_content"
      
android :id= "@+id/TabHost1" >
       <
LinearLayout
          
android :layout_width= "match_parent"
          
android :orientation= "vertical"
          
android :layout_height= "wrap_content" >

           <
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" >
          
FrameLayout >

      
LinearLayout >

  
TabHost >

RelativeLayout >

//设置标签页布局,注意红色和蓝色的标记

标签页布局1:tab1_layout

< LinearLayout android :layout_width= "match_parent"
   
android :layout_height= "match_parent"
   
android :orientation= "vertical"
   
android:id= "@+id/tabLinLayout1"
   
xmlns: android = "http://schemas.android.com/apk/res/android" >

    <
Button
       
android :layout_width= "match_parent"
       
android :layout_height= "wrap_content"
       
android :id= "@+id/btnBack"
       
android :text= "返回" />

LinearLayout >

标签页布局2:tab2_layout

xml version= "1.0" encoding= "utf-8" ?>
<
LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
   
android :layout_width= "match_parent"
   
android :layout_height= "match_parent"
   
android:id="@+id/tabLinLayout2" >

    <
Button
       
android :layout_width= "match_parent"
       
android :layout_height= "wrap_content"
       
android :id= "@+id/btn2Back"
       
android :text= "back" />

LinearLayout >

在java代码中的使用:

TabHost tabHost = (TabHost) findViewById(R.id. TabHost1 );
tabHost.setup();   
//启用

//声明布局文件,通过选取布局文件名方式
LayoutInflater layoutInflater = LayoutInflater.from( this );
layoutInflater.inflate(R.layout.
tab1_layout ,tabHost.getTabContentView());
layoutInflater.inflate(R.layout.
tab2_layout ,tabHost.getTabContentView());

//为布局设置id,配置标签时用id与标签绑定
tabHost.addTab(tabHost.newTabSpec( "tab1" ).
        setIndicator(
"标签1").setContent(R.id. tabLinLayout1 ));
tabHost.addTab(tabHost.newTabSpec(
"tab2" ).
        setIndicator( "标签2").setContent(R.id. tabLinLayout2));

你可能感兴趣的:(JAVA,Android)