I am new to android and Kotlin, developing a bottom navigation bar using onitemselectedListener, since setOnNavigationItemSelectedListener is deprecated and I couldn't find any youtube tutorial that explains how to used onitemselectedlistener for navigationbar. navigation shows up on the emulator, but fragments are not showing up when i click on navigation Icons. here are my codes.
adding image of activity_main and emulator error image
fragmentWord image, that is connected to the first icon of "A" but doesn't show up
MainActivity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.aryanvedh.vocabapp2.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val wordFragment = WordFragment()
val memorisedFragment = MemorisedFragment()
setCurrentFragment(wordFragment)
binding.bottomNavigationView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.words -> setCurrentFragment(wordFragment)
R.id.memorised -> setCurrentFragment(memorisedFragment)
}
true
}
}
private fun setCurrentFragment(fragment: Fragment) =
supportFragmentManager.beginTransaction().apply {
replace(R.id.flFragment, fragment)
commit()
}
}```
any help? thanks
You need to use the
OnNavigationItemSelectedListenerMethod to capture once the item is selected in Bottom Navigation.Here is the sample code attached from Documentation.
Please refer to the Official Documentation for more information about BottomNavigationView.