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;
}
});
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
}
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
}
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
}
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