I am trying to implement Nagivation from Android Architecture Components. I am able to navigate successfully across my fragments. I am trying to attach it to my bottom navigation but I am unable to use it properly. I can navigate between fragments successfully with Navigation.findNavController(View).navigate(R.id.Fragment)
but when I do that by using any UI component or back button, a highlight from my bottom navigation is not changing as shown in the following gif
My code is as follows for MainActivity.kt
,
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
navController.navigate(R.id.homeFragment)
return@OnNavigationItemSelectedListener true
}
R.id.navigation_dashboard -> {
navController.navigate(R.id.addEmotionFragment)
return@OnNavigationItemSelectedListener true
}
R.id.navigation_notifications -> {
return@OnNavigationItemSelectedListener true
}
}
false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navController = Navigation.findNavController(this, R.id.nav_host)
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
}
}
For HomeFragment.kt
class HomeFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
button.setOnClickListener {
Navigation.findNavController(it).navigate(R.id.addEmotionFragment)
}
}
}
Try to use navigation-ui.
implementation 'androidx.navigation:navigation-ui:' + navigationVersion //currently 1.0.0-alpha05
in activity
navController = Navigation.findNavController(this, R.id.nav_host)
NavigationUI.setupWithNavController(bottomNavigation, navController)
And make sure your fragment id match menu id.
<item
android:id="@+id/homeFragment"
android:title="Home"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With