所以我有3个模块
- 包含
BaseFragment
的模块:commons:ui
- 包含
HomeFragment
的模块:features:home
实现:commons:ui
- 包含
MainActivity
的模块:app
实现:features:home
如果我尝试在onCreate
中使用以下代码运行MainActivity
supportFragmentManager
.beginTransaction()
.add(R.id.fragment_container, HomeFragment())
.commit()
我得到错误
e: Supertypes of the following classes cannot be resolved. Please make sure you have the required
dependencies in the classpath:
class tech.vrutal.home.HomeFragment, unresolved supertypes: tech.vrutal.ui.BaseFragment
但是,如果我使用导航组件如下(删除MainActivity中的fragmentManager代码(
// activity_main.xml
<androidx.fragment.app.FragmentContainerView 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/fragment_container"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
// nav_graph.xml
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nav_graph"
app:startDestination="@id/home_fragment">
<fragment
android:id="@+id/home_fragment"
android:name="tech.vrutal.home.HomeFragment"
android:label="HomeFragment" />
</navigation>
现在它按预期工作
那么,为什么直接在MainActivity
中创建HomeFragment()
失败了,而使用导航组件只能很好地进行
我在一个非常相似的模块体系结构中遇到了这个问题。
我通过更改:features:home
的build.gradle
文件中的依赖声明解决了这个问题
来自
dependencies {
//...
implementation project(":commons:ui")
//...
}
至
dependencies {
//...
api project(":commons:ui")
//...
}
我在一天中多次遇到同样的错误。我不知道原因,也不知道如何解决,但每次我尝试第二次运行该应用程序时,它都会起作用。