为什么对于打开的片段我需要双击菜单项?
Why for open fragment I need double click to menu item?
我正在尝试使用 Kotlin 为 Android 设备创建底部导航栏。我学习了 Android 开发并且遇到了奇怪的行为。我的导航有效,但要打开下一个片段,我需要双击菜单项。我认为这部分代码的问题:
private val settingsFragment = SettingsFragment()
private val informationFragment = InformationFragment()
private val supportFragment = SupportFragment()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val bottom_navigation = findViewById<BottomNavigationView>(R.id.bottom_navigation)
replaceFragment(informationFragment)
bottom_navigation.setOnItemReselectedListener {
when(it.itemId){
R.id.app_info -> replaceFragment(informationFragment)
R.id.app_settings -> replaceFragment(settingsFragment)
R.id.app_support -> replaceFragment(supportFragment)
}
}
}
private fun replaceFragment(fragment: Fragment){
if(fragment != null){
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.fragment_container, fragment)
transaction.commit()
}
}
来自 val bottom_navigation = findViewById<BottomNavigationView>(R.id.bottom_navigation)
行。我是这么认为的,但我无法解决问题。因此,非常感谢您的帮助和解释。
请使用setOnItemSelectedListener
代替setOnItemReselectedListener
。
我正在尝试使用 Kotlin 为 Android 设备创建底部导航栏。我学习了 Android 开发并且遇到了奇怪的行为。我的导航有效,但要打开下一个片段,我需要双击菜单项。我认为这部分代码的问题:
private val settingsFragment = SettingsFragment()
private val informationFragment = InformationFragment()
private val supportFragment = SupportFragment()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val bottom_navigation = findViewById<BottomNavigationView>(R.id.bottom_navigation)
replaceFragment(informationFragment)
bottom_navigation.setOnItemReselectedListener {
when(it.itemId){
R.id.app_info -> replaceFragment(informationFragment)
R.id.app_settings -> replaceFragment(settingsFragment)
R.id.app_support -> replaceFragment(supportFragment)
}
}
}
private fun replaceFragment(fragment: Fragment){
if(fragment != null){
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.fragment_container, fragment)
transaction.commit()
}
}
来自 val bottom_navigation = findViewById<BottomNavigationView>(R.id.bottom_navigation)
行。我是这么认为的,但我无法解决问题。因此,非常感谢您的帮助和解释。
请使用setOnItemSelectedListener
代替setOnItemReselectedListener
。