我正在嘗試使用 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)線。我認為是這樣,但我無法解決問題。因此,我會非常感謝您的幫助和解釋。
uj5u.com熱心網友回復:
請使用setOnItemSelectedListener而不是setOnItemReselectedListener.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/460283.html
上一篇:即使在onAttach中將其初始化后,BottomSheetListener也會引發空指標例外
下一篇:具有多個片段的單個活動的后退按鈕
