Android開發之再探底部選單TabLayout與BottomNavigation實現方式

yungfan發表於2016-04-01

前文中已經對主流的底部選單實現進行了詳細說明,但隨著Android版本的升級,Google又推出了更方便的實現方式,此文就來一探究竟。

一、利用TabLayout來實現

TabLayout 我在Android開發之TabLayout實現頂部選單一文中是用來做頂部選單的。確實,Google設計出來本意是做頂部選單的,但是也可以作為底部選單來使用。注意與前文比較,只需要稍微修改一下Activity的佈局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <android.support.v4.view.ViewPager
        android:id="@+id/vp_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" /> //佔用上面,留出位置給TabLayout

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:background="#1FBCD2"
        //這兩句話一起使用 因為底部選單一般個數不多,使用這種方式,可以等分且居中
        app:tabGravity="fill"
        app:tabMode="fixed"
        //因為預設指示器在下面,不合適使用在底部選單所以直接設定其高度為0 
        app:tabIndicatorHeight="0dp"    
        app:tabSelectedTextColor="#FFFFFF"
        app:tabTextColor="#000000"></android.support.design.widget.TabLayout>

</LinearLayout>
複製程式碼

其餘地方不用變化,稍微修改一下底部選單的個數就可以了,我這裡就保留了4個,重複的程式碼我就不貼了,可以參考Android開發之TabLayout實現頂部選單

效果圖:

TabLayout Bottom.png

注意:這種方式實現起來確實比較簡單,不用再自己關聯ViewPager與底部選單的聯動。但是這種方式不太好定製指示器的位置,預設指示器在下方,按道理底部選單的時候應該在上方。我看了很多stackoverflow上面同樣的problem,試了都不太好使。如果哪位大俠能比較優雅地解決,可以私信我~~ 偷偷告訴你,在github上有個開源專案 FlycoTabLayout

二、利用Bottom navigation設計思路來實現

最近 Google 在Material Design設計規範中加入底部導航欄(Bottom navigation),真是千呼萬喚始出來啊,因為Google 給出的設計規範之前一直所提倡的是導航欄等相關要素應置於檢視頂部,蘋果提倡在底部,這次不知怎麼的,妥協了~然並卵,谷歌並沒有提供對應的控制元件來實現,用的比較多的還是github上的一個開源專案 Bottom Bar

相關文章