How to setOnNavigationItemListener on BottomNavigationView in android using Kotlin?

j.elmer picture j.elmer · Jun 18, 2017 · Viewed 19.2k times · Source

I use kotlin-android-extension and I can call bottomNavigationView id from layout file to kotlin file. I can use bottomNavigationView.setOnNavigationItemSelectedListener(BottomNavigationView.OnNavigationItemSelectedListener {}), but whats next?

As far as I know in Java, there is another function called onNavigationItemSelected, but I can't find it in kotlin.

this is the example code I want to use in Java but cannot write it in kotlin.

bottomNavigationView.setOnNavigationItemSelectedListener(
    new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.action_favorites:

                case R.id.action_schedules:

                case R.id.action_music:

            }
            return true;
        }
    });

Answer

Glory picture Glory · Jun 18, 2017

You can use this format of code:

bottomNavigation.setOnNavigationItemSelectedListener { item ->
    when (item.itemId) {
        R.id.action_favorites -> {
        }
        R.id.action_schedules -> {
        }
        R.id.action_music -> {
        }
    }
    true
}