歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中選項卡TabHost的基本使用

Android中選項卡TabHost的基本使用

日期:2017/3/1 10:49:40   编辑:Linux編程
今天來學習一下選項卡(TabHost)的使用,

選項卡的使用很常見,比如說:我們在手機上面 已接來電,未接來電的分組,首先來看下實現出來的效果截圖:

我們要去實現TabHost,主要有兩種方法:

1、各選項內容在布局文件中定義。
2、主Activity類繼承TabActivity;
3、用getTabHost()方法獲取TabHost

1、直接在布局文件中定義TabHost

注意:TabWidget的id必須是@Android:id/tabs,FrameLayout的id必須是 @android:id/tabcontent。


接下來使用第一種的實現方法來去實現TabHost

主Activity類:

  1. package com.jiangqq.tabhost;
  2. import android.app.TabActivity;
  3. import android.os.Bundle;
  4. import android.view.LayoutInflater;
  5. import android.widget.TabHost;
  6. import android.widget.TabHost.TabSpec;
  7. public class TabHostActivity_Second extends TabActivity {
  8. @Override
  9. protected void onCreate(Bundle savedInstanceState) {
  10. // TODO Auto-generated method stub
  11. super.onCreate(savedInstanceState);
  12. // setContentView(R.layout.tabhost_second);
  13. // 得到TabHost
  14. TabHost tabHost = this.getTabHost();
  15. // 把自己的布局文件添加到TabHost 的FrameLayout中 【注意】很重要的一句代碼
  16. LayoutInflater.from(this).inflate(R.layout.tabhost_second,
  17. tabHost.getTabContentView(), true);
  18. // 設置選項卡
  19. // 參數:是選項卡的標簽
  20. TabSpec parentSpec = tabHost.newTabSpec("parent");
  21. parentSpec.setIndicator("基類",
  22. this.getResources().getDrawable(R.drawable.announcements256));
  23. parentSpec.setContent(R.id.tab_1);
  24. TabSpec subSpec = tabHost.newTabSpec("sub");
  25. subSpec.setIndicator("子類",
  26. this.getResources().getDrawable(R.drawable.content256));
  27. subSpec.setContent(R.id.tab_2);
  28. tabHost.addTab(parentSpec);
  29. tabHost.addTab(subSpec);
  30. }
  31. }
TabHost的布局文件:
  1. package com.jiangqq.tabhost;
  2. import android.app.TabActivity;
  3. import android.os.Bundle;
  4. import android.view.LayoutInflater;
  5. import android.widget.TabHost;
  6. import android.widget.TabHost.TabSpec;
  7. public class TabHostActivity_Second extends TabActivity {
  8. @Override
  9. protected void onCreate(Bundle savedInstanceState) {
  10. // TODO Auto-generated method stub
  11. super.onCreate(savedInstanceState);
  12. // setContentView(R.layout.tabhost_second);
  13. // 得到TabHost
  14. TabHost tabHost = this.getTabHost();
  15. // 把自己的布局文件添加到TabHost 的FrameLayout中 【注意】很重要的一句代碼
  16. LayoutInflater.from(this).inflate(R.layout.tabhost_second,
  17. tabHost.getTabContentView(), true);
  18. // 設置選項卡
  19. // 參數:是選項卡的標簽
  20. TabSpec parentSpec = tabHost.newTabSpec("parent");
  21. parentSpec.setIndicator("基類",
  22. this.getResources().getDrawable(R.drawable.announcements256));
  23. parentSpec.setContent(R.id.tab_1);
  24. TabSpec subSpec = tabHost.newTabSpec("sub");
  25. subSpec.setIndicator("子類",
  26. this.getResources().getDrawable(R.drawable.content256));
  27. subSpec.setContent(R.id.tab_2);
  28. tabHost.addTab(parentSpec);
  29. tabHost.addTab(subSpec);
  30. }
  31. }
Copyright © Linux教程網 All Rights Reserved