Reputation: 1551
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)
}
}
}
Upvotes: 4
Views: 2383
Reputation: 1930
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"/>
Upvotes: 9
Reputation: 10125
You need to manually set a checked property inside your button click like:
button.setOnClickListener {
Navigation.findNavController(it).navigate(R.id.addEmotionFragment)
.... (Over Here)
}
The Java Code would be:
MenuItem menuItem = YourBottomViewObject.getMenu().getItem(1);
menuItemsetChecked(true);
MenuItem menuItem = YourBottomViewObject.getMenu().getItem(0);
menuItemsetChecked(false);
Upvotes: 2