底部導(dǎo)航BottomNavigation的使用

前言

BottomNavigation是MaterialDesign中的一個組件,能夠以menu的形式創(chuàng)建多個底部導(dǎo)航按鈕哆料,但是本質(zhì)上僅僅是對Menu的點擊事件的一個封裝而已憨降,一般自己寫的底部導(dǎo)航欄使用TextView或ImageView之類的控件描焰,然后設(shè)置View.OnClickListener設(shè)置點擊事件瘫证,對于BottomNavigationView來說咐容,它提供了setOnNavigationItemSelectedListener來設(shè)置每個item的點擊事件舆逃,所以用起來很簡單。下面介紹兩種常用的使用方法。

1.[Jetpack] Navigation + BottomNavigation

安卓官方推出的就是這種使用方式颖侄,用法經(jīng)過Jetpack的封裝鸟雏,使代碼看起來非常簡單,但是想要理解就得自己看源碼了览祖。下面介紹一下使用方法吧孝鹊。

  • gradle配置依賴
    之前說了BottomNavigationView是MaterialDesign里的控件,所以得引入第一個展蒂,其余四個則是[Jetpack]導(dǎo)航里的依賴又活。
    dependencies {
        implementation 'com.google.android.material:material:1.1.0' // BottomNavigation
        implementation 'androidx.navigation:navigation-fragment-ktx:2.2.1'
        implementation 'androidx.navigation:navigation-ui-ktx:2.2.1'
        implementation 'androidx.navigation:navigation-fragment:2.2.1'
        implementation 'androidx.navigation:navigation-ui:2.2.1'
        ......
    }
    
  • res目錄下創(chuàng)建menu
    BottomNavigationView不需要自己寫TextView之類的設(shè)置點擊事件,那View怎么來呢锰悼,就是通過MenuInflate引入的Menu的布局柳骄,然后通過MaterialDesign搞一波動畫效果,點擊效果之類的箕般,改成一個好看的風(fēng)格耐薯,給你使用。如下:bottom_nav_menu.xml
    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:id="@+id/navigation_home"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="@string/home" />
        <item
            android:id="@+id/navigation_dashboard"
            android:icon="@drawable/ic_dashboard_black_24dp"
            android:title="@string/dashboard" />
        <item
            android:id="@+id/navigation_notifications"
            android:icon="@drawable/ic_notifications_black_24dp"
            android:title="@string/notifications" />
    </menu>
    
    icon是矢量圖(就是傳說中放大無數(shù)倍都不會失真的圖哈哈哈)丝里,下面是代碼:
    ic_home_black_24dp.xml
    <vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
        <path
            android:fillColor="#FF000000"
            android:pathData="M10,20v-6h4v6h5v-8h3L12,3 2,12h3v8z" />
    </vector>
    
    ic_dashboard_black_24dp.xml
    <vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
        <path
            android:fillColor="#FF000000"
            android:pathData="M3,13h8L11,3L3,3v10zM3,21h8v-6L3,15v6zM13,21h8L21,11h-8v10zM13,3v6h8L21,3h-8z" />
    </vector>
    
    ic_notifications_black_24dp.xml
    <vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
        <path
            android:fillColor="#FF000000"
            android:pathData="M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.89,2 2,2zM18,16v-5c0,-3.07 -1.64,-5.64 -4.5,-6.32L13.5,4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.63,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2z" />
    </vector>
    
  • 寫好Fragment以及對應(yīng)的布局文件
    三個都是一樣的曲初,改改名字就好了,就不重復(fù)寫了
    HomeFragment.kt
    class HomeFragment : Fragment() {
        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            return inflater.inflate(R.layout.fragment_home, container, false)
        }
    }
    
    fragment_home.xml
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 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">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/home"
            android:textColor="@color/textColor"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • MainActivity使用BottomNavigationView
    MainActivity.kt
    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            initViews()
        }
    
        private fun initViews() {
            // host fragment
            val navController = findNavController(R.id.nav_host_fragment)
    
            // action bar <> fragment
            val appBarConfiguration = AppBarConfiguration(
                setOf(
                    R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications
                )
            )
            setupActionBarWithNavController(navController, appBarConfiguration)
    
            // bottom navigation <> fragment
            nav_view.setupWithNavController(navController)
        }
    }
    
    
    activity_main.xml
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".activity.MainActivity">
    
        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/nav_view"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="#FFFFFF"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:menu="@menu/bottom_nav_menu" />
    
        <fragment
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toTopOf="@+id/nav_view"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:navGraph="@navigation/mobile_navigation" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • navGraph:使用Jetpack導(dǎo)航
    jetpack實現(xiàn)了一種基于navController的導(dǎo)航方式杯聚,只要在res中新建一個navigation的目錄臼婆,將需要支持導(dǎo)航的Fragment聲明到該文件,然后傳入導(dǎo)航的itemid就可以進行導(dǎo)航幌绍,而且在navigation目錄中還能可視化颁褂,甚至還支持拖拽,不過本質(zhì)上都是切換Fragment方法的包裝而已傀广,只是方便你開發(fā)的時候看著舒服颁独。順便還幫你弄了一些切換fragment的效果,這個也是可以自定義的伪冰,相當(dāng)于加一些animation而已誓酒。廢話不多說了,下面是代碼:navigation/mobile_navigation.xml
    <?xml version="1.0" encoding="utf-8"?>
    <navigation xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/mobile_navigation"
        app:startDestination="@id/navigation_home">
    
        <fragment
            android:id="@+id/navigation_home"
            android:name="com.qi.fragment.home.HomeFragment"
            android:label="@string/home"
            tools:layout="@layout/fragment_home" />
        <fragment
            android:id="@+id/navigation_dashboard"
            android:name="com.qi.fragment.dashboard.DashboardFragment"
            android:label="@string/dashboard"
            tools:layout="@layout/fragment_dashboard" />
        <fragment
            android:id="@+id/navigation_notifications"
            android:name="com.qi.fragment.notifications.NotificationsFragment"
            android:label="@string/notifications"
            tools:layout="@layout/fragment_notifications" />
    </navigation>
    
  • 運行一下

2.[ViewPager] + BottomNavigation

這個就更簡單了糜值,沒有被jetpack封裝過的代碼顯得如此的簡單,清晰(哈哈哈坯墨,不是說Jetpack不好寂汇,只是用起來太過簡潔,讓我很難有學(xué)習(xí)的勁頭啊orz)
基于上面的代碼捣染,直接改一下Activity就好了
下面是代碼:
MainActivity.kt

class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      initViews()
  }

  private fun initViews() {
      val fragments = getFragments()
      vp.adapter = object : FragmentStateAdapter(this) {
          override fun getItemCount() = fragments.size

          override fun createFragment(position: Int) = fragments[position]
      }
      // 禁用左右滑動切換頁簽
      vp.isUserInputEnabled = false

      nav_view.setOnNavigationItemSelectedListener { item ->
          when (item.itemId) {
              R.id.navigation_home -> vp.currentItem = 0
              R.id.navigation_dashboard -> vp.currentItem = 1
              R.id.navigation_notifications -> vp.currentItem = 2
          }
          true
      }
  }

  private fun getFragments() =
      mutableListOf(HomeFragment(), DashboardFragment(), NotificationsFragment())
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".activity.MainActivity">

  <com.google.android.material.bottomnavigation.BottomNavigationView
      android:id="@+id/nav_view"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:background="#FFFFFF"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:menu="@menu/bottom_nav_menu" />

  <androidx.viewpager2.widget.ViewPager2
      android:id="@+id/vp"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layout_constraintBottom_toTopOf="@id/nav_view"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

總結(jié)

今天是看Jetpack源碼的第一天骄瓣,以我的感覺,Jetpack的navigation就是在原有的實現(xiàn)基礎(chǔ)上封裝了幾層耍攘,可能暫時我看的還不深入榕栏,所以對Jetpack的認識比較暫時停留在這兒畔勤。
還有一點忘說了,BottomNavigationView在綁定ViewPager使用的時候還有個bug扒磁,它必須設(shè)置禁止手動左右滑動庆揪,否則沒法與底部導(dǎo)航同步,我看了源碼妨托,并沒有提供解決辦法缸榛,所以還是別想著viewpager和jetpack的BottomNavigationView合在一起用了,還是TabLayout和ViewPager合在一起好用兰伤!
寫到這兒才發(fā)現(xiàn)標(biāo)題是使用BottomNavigationView内颗,說了半天Jetpack,就很尷尬敦腔,不管怎么說均澳,積極看源碼,順帶著自己debug一下符衔,收獲還是會有的找前。加油!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末柏腻,一起剝皮案震驚了整個濱河市纸厉,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌五嫂,老刑警劉巖颗品,帶你破解...
    沈念sama閱讀 221,273評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異沃缘,居然都是意外死亡躯枢,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,349評論 3 398
  • 文/潘曉璐 我一進店門槐臀,熙熙樓的掌柜王于貴愁眉苦臉地迎上來锄蹂,“玉大人,你說我怎么就攤上這事水慨〉妹樱” “怎么了?”我有些...
    開封第一講書人閱讀 167,709評論 0 360
  • 文/不壞的土叔 我叫張陵晰洒,是天一觀的道長朝抖。 經(jīng)常有香客問我,道長谍珊,這世上最難降的妖魔是什么治宣? 我笑而不...
    開封第一講書人閱讀 59,520評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上侮邀,老公的妹妹穿的比我還像新娘坏怪。我一直安慰自己,他們只是感情好绊茧,可當(dāng)我...
    茶點故事閱讀 68,515評論 6 397
  • 文/花漫 我一把揭開白布铝宵。 她就那樣靜靜地躺著,像睡著了一般按傅。 火紅的嫁衣襯著肌膚如雪捉超。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,158評論 1 308
  • 那天唯绍,我揣著相機與錄音拼岳,去河邊找鬼。 笑死况芒,一個胖子當(dāng)著我的面吹牛惜纸,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播绝骚,決...
    沈念sama閱讀 40,755評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼耐版,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了压汪?” 一聲冷哼從身側(cè)響起粪牲,我...
    開封第一講書人閱讀 39,660評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎止剖,沒想到半個月后腺阳,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,203評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡穿香,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,287評論 3 340
  • 正文 我和宋清朗相戀三年亭引,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片皮获。...
    茶點故事閱讀 40,427評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡焙蚓,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出洒宝,到底是詐尸還是另有隱情购公,我是刑警寧澤,帶...
    沈念sama閱讀 36,122評論 5 349
  • 正文 年R本政府宣布雁歌,位于F島的核電站宏浩,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏将宪。R本人自食惡果不足惜绘闷,卻給世界環(huán)境...
    茶點故事閱讀 41,801評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望较坛。 院中可真熱鬧印蔗,春花似錦、人聲如沸丑勤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,272評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽法竞。三九已至耙厚,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間岔霸,已是汗流浹背薛躬。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留呆细,地道東北人型宝。 一個月前我還...
    沈念sama閱讀 48,808評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像絮爷,于是被迫代替她去往敵國和親趴酣。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,440評論 2 359

推薦閱讀更多精彩內(nèi)容