在我的基本模块(应用程序)中,我有一些片段。我想将其中一个放在动态功能模块中,该模块将按需安装。在用户决定安装这个模块之前,我只会显示一个空的占位符而不是那个片段。我知道如果它是来自动态功能模块的活动很容易,但我真的需要在我的基本模块活动中显示这个片段。
这可能吗?
在我的基本模块(应用程序)中,我有一些片段。我想将其中一个放在动态功能模块中,该模块将按需安装。在用户决定安装这个模块之前,我只会显示一个空的占位符而不是那个片段。我知道如果它是来自动态功能模块的活动很容易,但我真的需要在我的基本模块活动中显示这个片段。
这可能吗?
您可以使用这种方式(Kotlin)
// example
val className: String
get() = "$MODULE_PACKAGE.ui.login.LoginFragment"
fun instantiateFragment(className: String) : Fragment? {
return try {
Class.forName(className).newInstance() as Fragment
} catch (e: Exception) {
// not install feature module
null
}
}
要启用应用模块和功能模块之间的交互,one can use dependency injection or service locator pattern
. 该应用程序可以找到功能模块的实现类和invokes its public API which returns the fragment instance in the app module and load that in main Activity's container
.
例如:在 app 中创建 Feature 接口,在 feature 模块中创建对应的 Impl。然后定位/注入这个 Impl 类实例并调用它的函数来获取片段引用。