Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android BottomNavigation is not highlighting properly with Navigation Controller

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

enter image description here

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)
        }
    }
}
like image 816
Dexter Avatar asked Dec 24 '22 04:12

Dexter


1 Answers

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"/>
like image 89
user345280 Avatar answered Dec 25 '22 23:12

user345280