i fixed the previous error but now this here. fragment isnt visible if i dont click bottom navigation two times. my code:
activity_main.xml
<androidx.fragment.app.FragmentContainerView
android:id="@ id/FragmentContainerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@ id/bottom_navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@ id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="@menu/bottom_navigation_menu" />
MainActivity.kt
binding.bottomNavigation.setOnItemReselectedListener { item ->
when(item.itemId) {
R.id.home -> {
replaceFragment(HomeFragment())
}
R.id.favs -> {
replaceFragment(FavsFragment())
}
}
}
}
private fun replaceFragment(fragment: Fragment) {
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.FragmentContainerView, fragment)
fragmentTransaction.commit()
}
CodePudding user response:
First we create navigation.xml (you can create navigation.xml if you click the ResourceManager button on the left, select navigation at the top and click the sign), then we name it my_nav and click the new destination button on the top and select all the fragments you will use. I suggest you to select your main fragment first
<fragment
android:id="@ id/fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="@ id/bottom_navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/my_nav" />
or try this
binding.bottomNavigation.setItemSelected(R.id.home, true)
by the way, some advice for you
binding.apply{
//If I do it this way, you don't need to write bindings for your objects every time.
//eg:
bottomNavigation.setOnItemReselectedListener { item ->
}
}
CodePudding user response:
Instead of setOnItemReselectedListener
you should use setOnItemSelectedListener
to avoid "double-clicking".
But you still have to add initial fragment to FragmentContainerView. For example, in onCreate()
you can call your replaceFragment()
with the fragment that you need to be shown at first.