天天看點

Android開發之再探底部菜單TabLayout與Bottom navigation實作方式

前文中已經對主流的底部菜單實作進行了詳細說明,但随着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與Bottom navigation實作方式

TabLayout Bottom.png

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

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

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

Bottom Bar

繼續閱讀