You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BottomNavigationView在XML预览可见但模拟器运行不显示问题求助

问题原因与解决方案

第一阶段控件不显示问题

你最开始的MainActivity.kt中onCreate方法未调用setContentView()绑定布局文件,Android Studio预览是直接渲染XML代码,运行时Activity没有加载布局,自然不会显示任何控件。

第二阶段运行异常问题

你修改后的代码存在2个核心错误:

  1. AppBarConfiguration构造参数错误:该方法需要传入导航图中定义的目的地ID(R.id.xxx格式),你传入的是R.layout开头的布局ID,类型不匹配会直接触发崩溃。
  2. 直接调用findNavController()获取导航控制器失败:对于FragmentContainerView承载的NavHostFragment,不能在onCreate阶段直接用findNavController找ID,需要先获取NavHostFragment实例再提取控制器。

正确代码示例

修正后的MainActivity.kt

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 若未开启ViewBinding可替换为 setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 正确获取NavController
        val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        val navController = navHostFragment.navController

        // 注意:此处替换为导航图中对应目的地的R.id格式ID,不要使用R.layout开头的布局ID
        val appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.news_feed_fragment, 
                R.id.friends_fragment, 
                R.id.messaging_fragment, 
                R.id.notifications_fragment, 
                R.id.menu_fragment
            )
        )
        setupActionBarWithNavController(navController, appBarConfiguration)
        // 未开启ViewBinding可替换为 findViewById<BottomNavigationView>(R.id.nav_view).setupWithNavController(navController)
        binding.navView.setupWithNavController(navController)
    }
}

额外检查项

  • 确认res/menu目录下存在bottom_nav_menu.xml,且每个菜单项的android:id和导航图里的目的地ID完全一致
  • 确认项目Module级build.gradle已添加匹配版本的依赖:
    // Material组件依赖
    implementation 'com.google.android.material:material:1.11.0'
    // Navigation组件依赖
    implementation 'androidx.navigation:navigation-fragment-ktx:2.7.7'
    implementation 'androidx.navigation:navigation-ui-ktx:2.7.7'
    

内容的提问来源于stack exchange,提问作者Zachary Smouse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 19:45:02