Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setOnNavigationItemListener on BottomNavigationView in android using Kotlin?

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;
        }
    });
like image 432
j.elmer Avatar asked Jun 18 '17 02:06

j.elmer


3 Answers

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
}
like image 85
Glory Avatar answered Nov 15 '22 05:11

Glory


You can use below code

bottom_navigation.setOnNavigationItemSelectedListener {
            var selectedFragment: Fragment = A()
            when (it.itemId) {
                R.id.action_item1 -> selectedFragment = A()
                R.id.action_item2 -> selectedFragment = B()
                R.id.action_item3 -> selectedFragment = C()
            }
            val transaction = fragmentManager.beginTransaction()
            transaction.replace(R.id.frame_layout, selectedFragment)
            transaction.commit()
            return@setOnNavigationItemSelectedListener true
        }
like image 29
Thanh vũ Avatar answered Nov 15 '22 05:11

Thanh vũ


use must add annotation for return the lambda only

 bottomNavigation.setOnNavigationItemSelectedListener { item ->
        when(item.itemId){
            R.id.home -> {}

            R.id.group -> {}

            R.id.profile -> {}
        }
        return true
    }
like image 7
Ali hasan Avatar answered Nov 15 '22 07:11

Ali hasan