Android学习笔记二:TabHost控件的使用说明收集

来源:互联网 发布:海湾设备现场编程 编辑:程序博客网 时间:2024/06/11 13:35

出处:http://blog.sina.com.cn/s/blog_6bec714e0100tv12.html



在使用了一个TabHost控件,下面我们来详细讲解下这个控件以及使用这个控件时,应该注意的一些问题。

使用TabHost有两种方法:

     一种是继承TabActivity;

     一种是不继承TabActivity;在这里我要讲解的是继承TabActivity的;首先我们得写好main.xml布局文件,在写这个布局文件时要注意,使用TabHost一定要有TabWidget、FramLayout这两个控件,并且TabWidget必须使用系统ID @android:id/tabs;FrameLayout作为标签内容的基本框架,也必须使用系统ID @android:id/tabcontent(TabWidget最好在FrameLayout上声时要不然TabWidget不会显示,但不会报错;而TabHost可以自定义ID,这是为了在系统初始化时能够使用,否则会报错!

示例一(最基本的)代码:

1)先建一个布局文件:res/layout/tab_demo.xml

 

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout

android:id="@+id/dd"
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:orientation="vertical" 
  android:layout_height="match_parent">
 
    <TextView android:id="@+id/tab_demo_tv1"   
        android:layout_width="fill_parent"    
        android:layout_height="fill_parent"    
        android:text="tab_demo_tv1"   
    />   
   <TextView android:id="@+id/tab_demo_tv2"   
        android:layout_width="fill_parent"    
        android:layout_height="fill_parent"    
        android:text="tab_demo_tv2"   
    />   
    <TextView android:id="@+id/tab_demo_tv3"   
        android:layout_width="fill_parent"    
        android:layout_height="fill_parent"    
        android:text="tab_demo_tv3"   
    />   
 
</FrameLayout>

 

2)

 tabHost = getTabHost();    
 tabHost.setBackgroundColor(Color.argb(150, 22, 70, 150));//设置背景

              LayoutInflater.from(this).inflate(R.layout.main, tabHost.getTabContentView(), true);  //初使化布局控件  

//R.layout.main 存放Tab布局

//通过TabHost获得存放Tab标签页内容的FrameLayout

//是否将inflate 拴系到根布局元素上


              tabHost.addTab(tabHost.newTabSpec("tab11").setIndicator("Tab1", getResources().getDrawable(R.drawable.abc)).setContent(R.id.tab_demo_tv1));  
              tabHost.addTab(tabHost.newTabSpec("tab22").setIndicator("Tab2", null).setContent(R.id.tab_demo_tv2));  
              tabHost.addTab(tabHost.newTabSpec("tab33").setIndicator("Tab3", null).setContent(R.id.tab_demo_tv3));  
//增加tab改变事件

              tabHost.setOnTabChangedListener(new OnTabChangeListener() {
    
    @Override
    public void onTabChanged(String s) {
     System.out.println(s+"s对应这里面设的名称tabHost.newTabSpec('tab11')---tab11");
     
    }
   });

 

示例二(最基本的通过Intent来改变Tab里的内容)代码:

1)res/layout/main.xml

<?xml version="1.0" encoding="UTF-8"?>
<TabHost android:id="@android:id/tabhost" android:layout_width="fill_parent"
 android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
 <LinearLayout android:orientation="vertical"
 android:background="#DADADA"
  android:layout_width="fill_parent" android:layout_height="fill_parent">
  
  <TabWidget android:id="@android:id/tabs"  android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="0.0" />
       <!-- 上下两个标签 是必须要有的-->
        <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="0.0dip" android:layout_weight="1.0" />
     
       
 </LinearLayout>
 
 
</TabHost>

 

2)

public class MainActivity extends TabActivity {
   
    TabHost tabs ; 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tabs = getTabHost(); 
       
        TabSpec tab2 = tabs.newTabSpec("TwoActivity");
        tab2.setIndicator("tab2");      // 设置tab1的名称    
        tab2.setContent(new Intent(MainActivity.this,TwoActivity.class));    // 关联控件    
        tabs.addTab(tab2); 
       
      //设置Tab1    
        TabSpec tab1 = tabs.newTabSpec("OneActivity");    
        tab1.setIndicator("tab1");      // 设置tab1的名称    
        tab1.setContent(new Intent(MainActivity.this,OneActivity.class));    // 关联控件    
        tabs.addTab(tab1);                // 添加tab1    
       
       
        TabSpec tab3 = tabs.newTabSpec("TwoActivity");
        tab3.setIndicator("tab3");      // 设置tab1的名称    
        tab3.setContent(new Intent(MainActivity.this,TwoActivity.class));    // 关联控件    
        tabs.addTab(tab3);
        tabs.setCurrentTab(0);    //显示一个Tab标签 作为当前的显示业
       
    }
}

 

问:下面我们来说明一下如何改变每个标签的大小和位置呢?如何设置每个标签的背景颜色或图片呢

 

    呵呵,在这里我们用getTabWidget()方法取TabWidget对象。通过该对象使用getChildAt(int i)来取得每个标签,取得每个标签之后,我们就可以使用下面代码来设置标签内容中的位置了:

 

变每个标签的大小和位置:

TabWidget mTabWidget = tabHost.getTabWidget();
    for(int i=0;i<mTabWidget.getChildCount();i++){

            //设置选项卡的宽度

               mTabWidget.getChildAt(i).getLayoutParams().height=50;

               //设置选项卡的高度

               mTabWidget.getChildAt(i).getLayoutParams().width=60;

       }


每个标签的背景颜色或图片:

 tabHost.addTab(tabHost.newTabSpec("tab33").setIndicator(createView("Tab3",R.drawable.abc)).setContent(R.id.tab_demo_tv3));  

 

public TextView createView(String str,int id){
     TextView text  = new TextView(this);
     text.setText(str);
     text.setTextSize(24);
     text.setBackgroundResource(id);
     return text;
     
    }

下面是效果




实现底部标签页切换功能:(说明:切换后的每个Activity后只会存在第一次创建的实例)


 

1)先声明一个TabHost布局:main.xml

<?xml version="1.0" encoding="UTF-8"?>
<TabHost android:id="@android:id/tabhost" android:layout_width="fill_parent"
 android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
 <LinearLayout android:orientation="vertical"
 android:background="#DADADA"
  android:layout_width="fill_parent" android:layout_height="fill_parent">
  
   <TabWidget android:id="@android:id/tabs" android:visibility="gone" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="0.0" />
      
        <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="0.0dip" android:layout_weight="1.0" />
     
        <include layout = "@layout/buttom" />  <!-- 导入一个底部模块 -->
 </LinearLayout>
 
 
</TabHost>

2)buttom.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent" android:layout_height="wrap_content">
 <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent" android:layout_height="wrap_content"
  android:stretchColumns="*">
  <TableRow>
   <Button android:id="@+id/left_button" android:text="One"
    android:gravity="center" android:textColor="#FF0101"
    android:layout_alignParentLeft="true" android:padding="5dip"
    android:background="@drawable/attend_cancel" android:layout_height="wrap_content" />
   <Button android:id="@+id/center_button" android:text="TWO"
    android:layout_marginLeft="1dip" android:gravity="center"
    android:textColor="#FF0101" android:padding="5dip"
    android:background="@drawable/attend_cancel" android:layout_height="wrap_content" />
   <Button android:id="@+id/right_button" android:text="Three"
    android:layout_marginLeft="1dip" android:gravity="center"
    android:textColor="#FF0101" android:padding="5dip"
    android:background="@drawable/attend_cancel" android:layout_height="wrap_content" />
  </TableRow>
 </TableLayout>

</LinearLayout>

3)创建四的Activity类:

MainActivity.java   OneActivity.java  ThreeActivity.java  TwoActivity.java

4)MainActivity.java代码:

public class MainActivity extends TabActivity implements OnClickListener{
   
    TabHost tabs ; 
    Button but1,but2,but3;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tabs = getTabHost(); 
     
       
      //设置Tab1    
        TabSpec tab1 = tabs.newTabSpec("OneActivity");    
        tab1.setIndicator("tab1");      // 设置tab1的名称    
        tab1.setContent(new Intent(MainActivity.this,OneActivity.class));    // 关联控件    
        tabs.addTab(tab1); 
        // 添加tab1    
       
       
        TabSpec tab2 = tabs.newTabSpec("TwoActivity");
        tab2.setIndicator("tab2");      // 设置tab1的名称    
        tab2.setContent(new Intent(MainActivity.this,TwoActivity.class));    // 关联控件    
        tabs.addTab(tab2); 
       
        TabSpec tab3 = tabs.newTabSpec("ThreeActivity");
        tab3.setIndicator("tab3");      // 设置tab1的名称    
        tab3.setContent(new Intent(MainActivity.this,ThreeActivity.class));    // 关联控件    
        tabs.addTab(tab3);
        tabs.setCurrentTab(0);    
       
        but1 =(Button)findViewById(R.id.left_button);
        but1.setOnClickListener(this);
        but2 =(Button)findViewById(R.id.center_button);
        but2.setOnClickListener(this);
        but3 =(Button)findViewById(R.id.right_button);
        but3.setOnClickListener(this);
  
    }
 
 @Override
 public void onClick(View view) {
  System.out.println("=");
  if(view == but1){

   //下面两种设定是一样的效果
     tabs.setCurrentTab(0);    
     //tabs.setCurrentTabByTag("OneActivity");
    
  }else if(view == but2){
   
     tabs.setCurrentTabByTag("TwoActivity");
  }else if(view == but3){
   
     tabs.setCurrentTabByTag("ThreeActivity");
  }else{
    tabs.setCurrentTab(0);    
  }
  
 }
   
}

 

这样就可以完成底部切换的功能了。

 

//下面是参考的一些博客网址

http://blog.csdn.net/ch_984326013/article/details/6602602

http://blog.csdn.net/hpoi/article/details/4647767

http://www.eoeandroid.com/thread-1035-1-1.html


出处:http://blog.csdn.net/chaihuasong/article/details/7639100

最近研究了一下Contacts源码,仿照上面自己写了一个TabHostTest程序,现整理如下:

main.xml布局文件:

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <TabHost xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:id="@android:id/tabhost"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent">  
  6.   
  7.     <LinearLayout  
  8.         android:orientation="vertical"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="match_parent">  
  11.   
  12.         <TabWidget android:id="@android:id/tabs"  
  13.             android:layout_width="match_parent"  
  14.             android:layout_height="wrap_content"  
  15.         />  
  16.   
  17.         <FrameLayout android:id="@android:id/tabcontent"  
  18.             android:layout_width="match_parent"  
  19.             android:layout_height="0dip"  
  20.             android:layout_weight="1"  
  21.         />  
  22.     </LinearLayout>  
  23. </TabHost>  


inner.xml文件:

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.   
  3. <TabHost xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:id="@android:id/tabhost"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent">  
  7.   
  8.     <LinearLayout  
  9.         android:orientation="vertical"  
  10.         android:layout_width="match_parent"  
  11.         android:layout_height="match_parent">  
  12. s  
  13.         <FrameLayout android:id="@android:id/tabcontent"  
  14.             android:layout_width="fill_parent"  
  15.             android:layout_height="0dip"  
  16.             android:layout_weight="1"  
  17.         />  
  18.           
  19.         <TabWidget android:id="@android:id/tabs"  
  20.             android:layout_width="fill_parent"  
  21.             android:layout_height="wrap_content"  
  22.         />  
  23.   
  24.   
  25.     </LinearLayout>  
  26. </TabHost>  

Main.Java (主Activity类):

[java] view plain copy
  1. package com.android.test;  
  2.   
  3. import android.app.Activity;  
  4. import android.app.TabActivity;  
  5. import android.content.Intent;  
  6. import android.os.Bundle;  
  7. import android.provider.CallLog.Calls;  
  8. import android.provider.Contacts.Intents.UI;  
  9. import android.view.Window;  
  10. import android.widget.TabHost;  
  11.   
  12. public class Main extends TabActivity implements TabHost.OnTabChangeListener {  
  13.     private static final int TAB_INDEX_DIALER = 0;  
  14.     private static final int TAB_INDEX_CALL_LOG = 1;  
  15.     private static final int TAB_INDEX_CONTACTS = 2;  
  16.     private static final int TAB_INDEX_FAVORITES = 3;  
  17.   
  18.     private TabHost mTabHost;  
  19.       
  20.     @Override  
  21.     public void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.   
  24.         final Intent intent = getIntent();  
  25.   
  26.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  27.           
  28.         setContentView(R.layout.main);  
  29.   
  30.         mTabHost = getTabHost();  
  31.         mTabHost.setOnTabChangedListener(this);  
  32.   
  33.         // Setup the tabs  
  34.         setupDialerTab();  
  35.         setupCallLogTab();  
  36.         setupContactsTab();  
  37.         setupFavoritesTab();  
  38.   
  39.         setCurrentTab(intent);  
  40.     }  
  41.   
  42.     public void onTabChanged(String tabId) {  
  43.          Activity activity = getLocalActivityManager().getActivity(tabId);  
  44.             if (activity != null) {  
  45.                 activity.onWindowFocusChanged(true);  
  46.             }  
  47.     }  
  48.      private void setupCallLogTab() {  
  49.             // Force the class since overriding tab entries doesn't work  
  50.             Intent intent = new Intent("com.android.phone.action.RECENT_CALLS");  
  51.   
  52.             intent.setClass(this, Inner.class);  
  53.             mTabHost.addTab(mTabHost.newTabSpec("call_log")  
  54.                     .setIndicator("通话记录",  
  55.                             getResources().getDrawable(R.drawable.ic_tab_unselected_recent))  
  56.                     .setContent(intent));  
  57.         }  
  58.        
  59.     private void setupDialerTab() {  
  60.         Intent intent = new Intent("com.android.phone.action.TOUCH_DIALER");  
  61.         intent.setClass(this, Inner.class);  
  62.   
  63.         mTabHost.addTab(mTabHost.newTabSpec("dialer")  
  64.                 .setIndicator("拨号",  
  65.                         getResources().getDrawable(R.drawable.ic_tab_unselected_dialer))  
  66.                 .setContent(intent));  
  67.     }  
  68.   
  69.     private void setupContactsTab() {  
  70.         Intent intent = new Intent(UI.LIST_DEFAULT);  
  71.         intent.setClass(this, Main.class);  
  72.   
  73.         mTabHost.addTab(mTabHost.newTabSpec("contacts")  
  74.                 .setIndicator("通讯录",  
  75.                         getResources().getDrawable(R.drawable.ic_tab_unselected_contacts))  
  76.                 .setContent(intent));  
  77.     }  
  78.   
  79.     private void setupFavoritesTab() {  
  80.         Intent intent = new Intent(UI.LIST_STREQUENT_ACTION);  
  81.         intent.setClass(this, Inner.class);  
  82.   
  83.         mTabHost.addTab(mTabHost.newTabSpec("favorites")  
  84.                 .setIndicator("收藏",  
  85.                         getResources().getDrawable(R.drawable.ic_tab_unselected_starred))  
  86.                 .setContent(intent));  
  87.     }  
  88.   
  89.     /** 
  90.      * Sets the current tab based on the intent's request type 
  91.      * 
  92.      * @param intent Intent that contains information about which tab should be selected 
  93.      */  
  94.     private void setCurrentTab(Intent intent) {  
  95.         // Dismiss menu provided by any children activities  
  96.         Activity activity = getLocalActivityManager().  
  97.                 getActivity(mTabHost.getCurrentTabTag());  
  98.         if (activity != null) {  
  99.             activity.closeOptionsMenu();  
  100.         }  
  101.   
  102.         // Tell the children activities that they should ignore any possible saved  
  103.         // state and instead reload their state from the parent's intent  
  104.         intent.putExtra(""true);  
  105.   
  106.         // Choose the tab based on the inbound intent  
  107.         String componentName = intent.getComponent().getClassName();  
  108.         if (getClass().getName().equals(componentName)) {  
  109.             if (false) {  
  110.                //in a call, show the dialer tab(which allows going back to the call)  
  111.                 mTabHost.setCurrentTab(TAB_INDEX_DIALER);  
  112.             } else if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {  
  113.                 // launched from history (long-press home) --> nothing to change  
  114.             } else if (true) {  
  115.                 // The dialer was explicitly requested  
  116.                 mTabHost.setCurrentTab(TAB_INDEX_DIALER);  
  117.             }   
  118.         }  
  119.     }  
  120. }  

Inner.java类:

[java] view plain copy
  1. package com.android.test;  
  2.   
  3. import android.app.TabActivity;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.view.Window;  
  7. import android.widget.TabHost;  
  8. import android.widget.TabWidget;  
  9. import android.widget.TextView;  
  10.   
  11. public class Inner extends TabActivity implements TabHost.OnTabChangeListener {  
  12.     private static final int TAB_INDEX_ALL = 0;  
  13.     private static final int TAB_INDEX_MISSED = 1;  
  14.     private static final int TAB_INDEX_OUTGOING = 2;  
  15.     private static final int TAB_INDEX_RECEIVED = 3;  
  16.   
  17.     private TabHost mTabHost;  
  18.     private TabWidget mTabWidget;  
  19.       
  20.     @Override  
  21.     public void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  24.         setContentView(R.layout.inner);  
  25.   
  26.         mTabHost = getTabHost();  
  27.         mTabHost.setOnTabChangedListener(this);  
  28.   
  29.         setupTabs();  
  30.         mTabWidget = mTabHost.getTabWidget();  
  31.         mTabWidget.setStripEnabled(false);  
  32.   
  33.         for (int i = 0; i < mTabWidget.getChildCount(); i++) {  
  34.   
  35.             TextView tv = (TextView) mTabWidget.getChildAt(i).findViewById(  
  36.                     android.R.id.title);  
  37.             tv.setTextColor(this.getResources().getColorStateList(  
  38.                     android.R.color.white));  
  39.               
  40.             tv.setPadding(000,(int) tv.getTextSize());  
  41.             tv.setText("Tab" + i);  
  42.             mTabWidget.getChildAt(i).getLayoutParams().height =(int ) (3* tv.getTextSize());  
  43.    
  44.             mTabWidget.getChildAt(i).setBackgroundResource(R.drawable.tab_bg);  
  45.         }  
  46.     }  
  47.   
  48.     public void onTabChanged(String tabId) {  
  49.           
  50.     }  
  51.   
  52.     private void setupTabs() {  
  53.         mTabHost.addTab(mTabHost.newTabSpec("all").setIndicator(  
  54.                 getString(R.string.inner)).setContent(  
  55.                 new Intent(this, Other.class)));  
  56.         mTabHost.addTab(mTabHost.newTabSpec("Missed").setIndicator(  
  57.                 getString(R.string.inner)).setContent(  
  58.                 new Intent(this, Other.class)));  
  59.         mTabHost.addTab(mTabHost.newTabSpec("Outgoing").setIndicator(  
  60.                 getString(R.string.inner)).setContent(  
  61.                 new Intent(this, Other.class)));  
  62.         mTabHost.addTab(mTabHost.newTabSpec("Received").setIndicator(  
  63.                 getString(R.string.inner)).setContent(  
  64.                 new Intent(this, Other.class)));  
  65.   
  66.     }  
  67. }  

效果图如下:




0 0
原创粉丝点击