<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<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"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:itemTextColor="@color/color_state_menu_nav"
/>
<fragment
android:id="@+id/nav_main_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
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/nav_home" />
</androidx.constraintlayout.widget.ConstraintLayout>
在xml中BottomNavigationView的app:menu="@menu/bottom_nav_menu"属性不再使用,而通过以下代码动态设置:
private fun initBottomNavigationView(){
if(PreferenceManager.getAccountType().equals(Constant.ACCOUNT_TYPE_1) || PreferenceManager.getAccountType().equals(Constant.ACCOUNT_TYPE_2)){
mBinding!!.navView.inflateMenu(R.menu.bottom_nav_menu_farmer)
}else{
mBinding!!.navView.inflateMenu(R.menu.bottom_nav_menu_expert)
}
}
private var mBinding: ActivityMainBinding?=null
private var navController: NavController?=null
private var navGraph: NavGraph?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
navController = findNavController(R.id.nav_main_fragment)
navGraph = navController!!.graph
mBinding!!.navView.setupWithNavController(navController!!)
}