我想尝试新的导航库。关注后本指南 https://developer.android.com/topic/libraries/architecture/navigation/navigation-implementing我在运行时遇到错误:
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 中的库(导航除外),因为它可能尚未迁移。我在 Google 上唯一能找到的地方androidx.navigation
is here https://developer.android.com/jetpack/docs/getting-started。不幸的是 Gradle 无法下载它。
Edit
我的内部还启用了 jetifier 工具gradle.properties
.
android.enableJetifier=true
android.useAndroidX=true
Update
它已在 Android Studio 3.2 Canary 17 中修复,如中所述这个答案 https://stackoverflow.com/a/50385411/4386668。不要忘记使缓存失效并重新启动以删除代码中的警告。