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

XML中NavHostFragment无法访问的运行时报错问题排查

解决NavHostFragment实例化失败的InflateException问题

我在尝试接入新的Navigation库时,严格按照官方指南操作,结果运行App时遇到了以下报错:

Caused by: android.view.InflateException: Binary XML file line #11: Binary XML file line #11: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class fragment
Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment androidx.navigation.fragment.NavHostFragment: make sure class name exists, is public, and has an empty constructor that is public

这个报错指向我的activity_home.xml文件,文件内容如下:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.home.HomeActivity">

    <fragment
        android:id="@+id/fragment_navigation_host"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:defaultNavHost="true"
        app:navGraph="@navigation/navigation_home" />

</FrameLayout>

排查过程中,我发现NavHostFragment源码依赖的是android.support.v4.app.Fragment,但我的整个项目都在使用androidx.fragment.app.Fragment,这让我怀疑是兼容性问题。我的依赖配置如下:

// AndroidX
implementation "androidx.appcompat:appcompat:$appCompatVersion"
implementation "androidx.constraintlayout:constraintlayout:$constraintLayoutVersion"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycleVersion"
implementation "androidx.recyclerview:recyclerview:$recyclerViewVersion"
implementation "androidx.room:room-runtime:$roomVersion"
implementation "androidx.room:room-rxjava2:$roomVersion"
kapt "androidx.room:room-compiler:$roomVersion"

// Navigation
implementation "android.arch.navigation:navigation-fragment-ktx:$navigationVersion"
implementation "android.arch.navigation:navigation-ui-ktx:$navigationVersion"

可以看到,除了Navigation库,其他依赖都是AndroidX版本——我之前以为Navigation库还没完成AndroidX迁移,后来找到了androidx.navigation的依赖,但Gradle一直无法下载对应的包。另外,我的gradle.properties已经启用了Jetifier工具:

android.enableJetifier=true
android.useAndroidX=true

问题解决更新

这个兼容性问题已经在Android Studio 3.2 Canary 17版本中得到修复。解决步骤如下:

  1. 升级Android Studio到3.2 Canary 17或更高版本
  2. 将Navigation库的依赖替换为AndroidX版本:
    implementation "androidx.navigation:navigation-fragment-ktx:$navigationVersion"
    implementation "androidx.navigation:navigation-ui-ktx:$navigationVersion"
    
  3. 清除Android Studio缓存并重启IDE,这样可以消除残留的代码警告

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:41:43