我想尝试新的导航库。按照这个指南操作后,我在运行时遇到了错误:
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"
正如您所看到的,我正在使用AndroidX库,除了Navigation以外,因为它可能还没有迁移。我能在Google上找到androidx.navigation的唯一位置是这里。不幸的是,Gradle无法下载它。
编辑
我还在我的gradle.properties
中启用了jetifier工具。
android.enableJetifier=true
android.useAndroidX=true
更新
如此答案所述,问题已在Android Studio 3.2 Canary 17中得到解决。请不要忘记使缓存失效并重新启动以去除代码中的警告。