標籤:android tabhost 底部導覽列 xml 方法
在App應用中,導覽列往往是用於解決功能分塊的最佳控制項,而底部導覽列更是導覽列中最常用的,因為它位於螢幕底部,使用者操作起來會很方便。
下面介紹一下使用Android控制項TabHost實現底部導覽列的方法。
TabHost可以在控制項陳列庫裡直接拖到頁面上,非常方便,但拖出來的是頂部導覽列,如所示:
到這裡就可以開始實現底部導覽列了,我們首先轉到它的XML布局代碼裡,然後修改成下面這樣:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.tabhosttest.MainActivity" tools:ignore="MergeRootFrame" > <TabHost android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <FrameLayout android:id="@android:id/tabcontent" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:id="@+id/tab1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> <LinearLayout android:id="@+id/tab2" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> <LinearLayout android:id="@+id/tab3" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> </FrameLayout> <TabWidget android:id="@android:id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" > </TabWidget> </LinearLayout> </TabHost></FrameLayout>
修改的地方就是把TabWinget放到了FrameLayout下面。我們可以看一下Layout的介面層次,這是更改前的:
最外面的是介面的總FrameLayout,然后里麵包含了一個TabHost,而這個TabHost裡面有一個線性垂直布局LinearLayout,裡面布局了兩個部分的東西,一個是顯示介面tabcontent,一個按鈕控制項tabs,現在是頂部導覽列,因為tabs在tabcontent上面,所以當我們要實現底部導覽列的時候,只需要把tabs改成在tabcontent的下面即可,改完後的層次圖:
此時雖然在層次圖上我們可以看到tabs在tabcontent下面,但遠遠沒有大功告成,因為現在整個介面已經變成白色了,沒有任何控制項顯示出來。原因出現tabcontent是一個FrameLayout,而這個Layout此時的height是match_parent,也就是說它一個就把整個頁面全佔了。所以下面我們要解決的就是tabcontent和tabs的比例顯示問題。
我使用的方法是通過調整tabcontent和tabs的Weight(權重),我將tabcontent的weight調整為0.8,tabs不變,此時tabs就可以顯示出來了(比例可更改),效果
關於Weight這個屬性,大家可以看看下面這兩句話,如果需要更詳細的的說明,可以去看看原文,後面附錄了地址:
在layout_width設置為fill_parent的時候,layout_weight所代表的是你的控制項要優先盡可能的大,但這個大是有限度的,即fill_parent.
在layout_width設置為wrap_content的時候,layout_weight所代表的是你的控制項要優先盡可能的小,但這個小是有限度的,即wrap_content.
layout_height 同 layout_width.
原文地址
【Android基礎篇】TabHost實現底部導覽列