gpt4 book ai didi

Android BottomNavigation 未使用导航 Controller 正确突出显示

转载 作者:太空宇宙 更新时间:2023-11-03 12:44:15 26 4
gpt4 key购买 nike

我正在尝试实现 Nagivation来自 Android 架构组件。我能够成功地浏览我的 fragment 。我试图将它附加到我的底部导航,但我无法正确使用它。我可以使用 Navigation.findNavController(View).navigate(R.id.Fragment) 在 fragment 之间成功导航,但是当我使用任何 UI 组件或后退按钮执行此操作时,底部导航的突出显示是没有变化,如下图所示

enter image description here

我的MainActivity.kt代码如下,

class MainActivity : AppCompatActivity() {


private lateinit var navController: NavController


private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
navController.navigate(R.id.homeFragment)
return@OnNavigationItemSelectedListener true
}
R.id.navigation_dashboard -> {
navController.navigate(R.id.addEmotionFragment)
return@OnNavigationItemSelectedListener true
}
R.id.navigation_notifications -> {
return@OnNavigationItemSelectedListener true
}
}
false
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navController = Navigation.findNavController(this, R.id.nav_host)
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
}


}

对于 HomeFragment.kt

class HomeFragment : Fragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false)
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)

button.setOnClickListener {
Navigation.findNavController(it).navigate(R.id.addEmotionFragment)
}
}
}

最佳答案

尝试使用navigation-ui。

implementation 'androidx.navigation:navigation-ui:' + navigationVersion //currently 1.0.0-alpha05

在 Activity 中

    navController = Navigation.findNavController(this, R.id.nav_host)
NavigationUI.setupWithNavController(bottomNavigation, navController)

并确保您的 fragment ID 与菜单 ID 匹配。

<item
android:id="@+id/homeFragment"
android:title="Home"/>

关于Android BottomNavigation 未使用导航 Controller 正确突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51915159/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com