底部导航栏BottomNavigationView

孙经艺
2023-12-01

项目中一直使用的是TabHost来做的底部导航栏,最近项目语言换成kotlin发现TabHost不推荐使用了,于是找到了BottomNavigationView+Fragment的方式,简单,便捷!

第一种方式:BottomNavigationView+FramLayout

1.依赖

implementation "com.google.android.material:material:${versions.material}"

2.布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".module.main.MainActivity">
    <FrameLayout
        android:id="@+id/ll_fragmentLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/bottomNavigationView"/>
    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:itemTextColor="@drawable/bottom_navigation_item_selector"
        app:menu="@menu/main_bottom_navigation"/>
</RelativeLayout>

3.meun文件配置

<?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"
    xmlns:tools="http://schemas.android.com/tools">
    <item
        android:id="@+id/menu_home"
        android:enabled="true"
        android:icon="@drawable/selector_btn_home"
        android:title="首页"
        app:showAsAction="ifRoom"
        tools:ignore="DuplicateIds" />
    <item
        android:id="@+id/menu_message"
        android:enabled="true"
        android:icon="@drawable/selector_btn_message"
        android:title="消息"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/menu_mine"
        android:enabled="true"
        android:icon="@drawable/selector_btn_mine"
        android:title="我的"
        app:showAsAction="ifRoom" />
</menu>

4.Activity配置

class MainActivity : BaseActivity<ActivityMainBinding>(ActivityMainBinding::inflate) {
    private var lastIndex = 0
    private var mFragments = mutableListOf<Fragment>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initData()
        initBottomNavivation()
    }

    fun initData(){
        mFragments = ArrayList();
        mFragments.add(HomeFragment())
        mFragments.add(MessageFragment())
        mFragments.add(MineFragment())
        setFragmentPostion(0)
    }

    fun initBottomNavivation(){
        viewBinding.bottomNavigationView.itemIconTintList = null  //设置图标默认颜色
        viewBinding.bottomNavigationView.itemBackground = null   //设置点击动背景
        viewBinding.bottomNavigationView.setOnNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.menu_home -> {
                    setFragmentPostion(0)
                    return@setOnNavigationItemSelectedListener true
                }
                R.id.menu_message -> {
                    setFragmentPostion(1)
                    return@setOnNavigationItemSelectedListener true
                }
                R.id.menu_mine -> {
                    setFragmentPostion(2)
                    return@setOnNavigationItemSelectedListener true
                }
            }
            false
        }
    }

    fun setFragmentPostion(postion:Int){
        val ft = supportFragmentManager.beginTransaction()
        val currentFragment = mFragments[postion]
        val lastFragment = mFragments[lastIndex]
        lastIndex = postion
        ft.hide(lastFragment)
        if(!currentFragment.isAdded){
            supportFragmentManager.beginTransaction().remove(currentFragment).commit()
            ft.add(R.id.ll_fragmentLayout,currentFragment)
        }
        ft.show(currentFragment)
        ft.commitAllowingStateLoss()
    }


    override fun getPageName(): String {
        return PageName.MAIN
    }

}

第二种方式:BottomNavigationView+fragment标签

1.依赖

def nav_version = "2.3.5"

  // Java language implementation
  implementation "androidx.navigation:navigation-fragment:$nav_version"
  implementation "androidx.navigation:navigation-ui:$nav_version"

  // Kotlin
  implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
  implementation "androidx.navigation:navigation-ui-ktx:$nav_version"

  // Feature module Support
  implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"

  // Testing Navigation
  androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"

  // Jetpack Compose Integration
  implementation "androidx.navigation:navigation-compose:2.4.0-beta02"

2.layout
 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:paddingTop="?attr/actionBarSize"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:background="@color/white"
        app:menu="@menu/main_bottom_navigation"/>
    <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="false"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>

3.navigation
 

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:startDestination="@+id/menu_home"
    android:id="@+id/mobile_navigation">
    <fragment
        android:id="@+id/menu_home"
        android:name="com.huishouqian.merchant.module.home.HomeFragment"
        tools:layout="@layout/fragment_home"/>

    <fragment
        android:id="@+id/menu_message"
        android:name="com.huishouqian.merchant.module.message.MessageFragment"
        tools:layout="@layout/fragment_message"/>

    <fragment
        android:id="@+id/menu_mine"
        android:name="com.huishouqian.merchant.module.mine.MineFragment"
        tools:layout="@layout/fragment_mine"/>
</navigation>

4.Activity

class NavigationViewActivity:BaseActivity<ActivityNavagationViewBinding>(ActivityNavagationViewBinding::inflate) {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewBinding.navView.itemIconTintList = null
        viewBinding.navView.itemBackground = null
        val appBarConfiguration = AppBarConfiguration(setOf(R.id.menu_home,R.id.menu_message,R.id.menu_mine))
        val navController = findNavController(R.id.nav_host_fragment)
        setupActionBarWithNavController(navController,appBarConfiguration)
        viewBinding.navView.setupWithNavController(navController)

    }

    override fun getPageName(): String {
        return ""
    }
}

第二种方式在开发过程中遇见的问题

1.报错

no start destination defined via app:startDestination for com.xxx.xxx/mobile_navigation

解决方法:在navigation的根目录上加入startDestiantion = "@+id/menu_home"标签

2.报错

java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference

需要在AndroidManifest中给Activity添加一个带ActionBar的主题

3.navigation 中item的id需要和menu文件中的item的id保持一直,否则Fragment切换会出问题。

 类似资料: