Issue
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()
}
Solution
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.
Answered By - Stepan Kulagin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.