Material Design

Material Design Bottom Navigation

1.先導入函示庫(build.gradle: Module)

dependencies {
   implementation 'com.google.android.material:material:1.2.0-alpha05'
}

2.程式碼範例

a.創建menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/home"
        android:icon="@drawable/home"
        android:title="首頁" />
    <item android:title="聊天"
        android:icon="@drawable/chat"
        android:id="@+id/chat"/>
    <item android:title="獎勵"
        android:icon="@drawable/bonus"
        android:id="@+id/bonus"/>
    <item android:title="個人"
        android:icon="@drawable/personal"
        android:id="@+id/personal"/>
</menu>

b.layout聲明BottomNavigationView

<com.google.android.material.bottomnavigation.BottomNavigationView
        app:itemTextColor="@color/colorPrimaryDark"
        android:background="@color/colorBg"
        android:id="@+id/bottomBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/menu" />

c. Bottom navigation設置監聽

  //讓bottomNavigation可以顯示原圖
  bottomBar.itemIconTintList = null

  bottomBar.setOnNavigationItemSelectedListener {
            item ->
            when(item.itemId) {
                R.id.home -> {
                    page_name.text = item.title
                    supportFragmentManager.beginTransaction().replace(R.id.fragment, HomeFragment.instance).commit()
                    true
                }

                R.id.chat -> {
                    page_name.text = item.title
                    supportFragmentManager.beginTransaction().replace(R.id.fragment, ChatFragment.instance).commit()
                    true
                }

                R.id.bonus -> {
                    page_name.text = item.title
                    supportFragmentManager.beginTransaction().replace(R.id.fragment, BonusFragment.instance).commit()
                    true
                }
                else -> {
                    page_name.text = item.title
                    supportFragmentManager.beginTransaction().replace(R.id.fragment, PersonalFragment.instance).commit()
                    true
                }
            }
        }

4.效果展示

發表迴響