天天看點

模仿微信界面tabhost底部導航——使用繼承ActivityGroup方式

在一般常見的app中,常常會用到底部導航,而android預設的是頂部導航。目前的android版本中,已經不再推薦使用extends TabActivity的方式來建立tabhost,但作為比較常見的一種方式,還是在自己做項目的過程中總結一下。

需要注意的是,每個tabhost頁籤可能是由一個Intent啟動的,此時每個頁籤對應一個Activity.廢話不多說,帖代碼!

Activity:

public class MainActivity extends ActivityGroup{
 
 private TabHost tabHost;
 //資源檔案
 private Class[] activitys = {TabActivity_book.class, TabActivity_search.class, TabActivity_account.class};
 private String[] titles = {"機票預訂", "訂單查詢", "我的賬号"};
 private int[] images = {R.drawable.book, R.drawable.search, R.drawable.account};
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  //初始化tab标簽
  tabHost = (TabHost) findViewById(R.id.mytabhost);
  tabHost.setup(this.getLocalActivityManager());//表明繼承TabActivity,由于隻能單繼承,是以隻好在這裡寫
  //建立标簽
  for(int i=0; i<activitys.length; i++) {
   View view = View.inflate(this, R.layout.tab_layout, null);
   //設定imageView
   ImageView imageView = (ImageView) view.findViewById(R.id.image);
//   imageView.setImageDrawable(getResources().getDrawable(images[i]));
   //設定textView
   TextView textView = (TextView) view.findViewById(R.id.title);
   textView.setText(titles[i]);
   //設定跳轉的Intent
   Intent intent = new Intent(this, activitys[i]);
   //設定TabSpec
   TabSpec spec = tabHost.newTabSpec(titles[i]).setIndicator(view).setContent(intent);
   
   tabHost.addTab(spec);
  }
 }
           

布局檔案:

<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/mytabhost"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">
 
     <!-- 需要一個布局管理器 -->
  
     <RelativeLayout
         android:layout_width="fill_parent"
         android:layout_height="fill_parent" 
         >
         
                 <!--
        由于TabHost是繼承于FrameLayout,是以需要一個FrameLaytout布局(内容頁) ,id
        必須為tabcontent
         -->
     <FrameLayout
             android:id="@android:id/tabcontent"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent" 
             >
         </FrameLayout>
       
 
         <!-- TabWidget必須标簽,用來存放tab标簽,且id必須為tabs -->
 
         <TabWidget
             android:id="@android:id/tabs"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:background="@drawable/tab_widget_background"
             android:layout_alignParentBottom="true"
             >
   <!-- android:layout_alignParentBottom="true" -->
         </TabWidget>
          
     </RelativeLayout>
 
 </TabHost>      

注意:

1. activity還能繼承自TabHost,此時activity中擷取tabhost的代碼可這樣寫:tabHost = getTabHost(),但同時布局檔案中tabhost的id必須使用系統自定義的Id:android:id="@android:id/tabhost"

2. 要使導航位于底部,FrameLaytout(内容頁)必須放在TabWidget上面。

效果圖:

模仿微信界面tabhost底部導航——使用繼承ActivityGroup方式