目前存在官方bug,BottomNavigationView点击切换时,fragment重复执行onCreateView
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| <?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">
<com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottom_nav_view" android:layout_width="match_parent" android:layout_height="60dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:menu="@menu/bottom_menu" android:orientation="horizontal" android:background="?android:attr/windowBackground" app:itemIconTint="@drawable/selector_bottom_navigation" app:itemTextColor="@drawable/selector_bottom_navigation"/>
<androidx.fragment.app.FragmentContainerView android:id="@+id/my_fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginBottom="60dp" app:defaultNavHost="true" app:navGraph="@navigation/navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/f1" android:icon="@drawable/icon_1" android:contentDescription="home" android:title="home" /> <item android:id="@+id/f2" android:icon="@drawable/icon_2" android:contentDescription="project" android:title="project" /> <item android:id="@+id/f3" android:icon="@drawable/icon_3" android:contentDescription="personal" android:title="personal" /> </menu>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <?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/navigation.xml" app:startDestination="@id/f1">
<fragment android:id="@+id/f1" android:name="com.stew.kotlinjetpack.navigation.Test1Fragment" tools:layout="@layout/fragment_test1"/>
<fragment android:id="@+id/f2" android:name="com.stew.kotlinjetpack.navigation.Test2Fragment" tools:layout="@layout/fragment_test2"/>
<fragment android:id="@+id/f3" android:name="com.stew.kotlinjetpack.navigation.Test3Fragment" tools:layout="@layout/fragment_test3"/>
</navigation>
|
1 2 3
| val f = supportFragmentManager.findFragmentById(R.id.my_fragment) as NavHostFragment
findViewById<BottomNavigationView>(R.id.bottom_nav_view).setupWithNavController(f.navController)
|