问题描述
在我的基本模块(应用程序)中,我有一些片段。我想将其中一个放在动态功能模块中,该模块将按需安装。在用户决定安装此模块之前,我将只显示一个空的占位符而不是该Fragment。我知道如果这是动态功能模块中的活动,这很容易,但是我真的需要在基本模块活动中显示此片段。
这可能吗?
解决方法
您可以使用这种方式(科特琳)
// 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
。
例如:在应用程序中创建功能界面,并在功能模块中创建相应的Impl。然后找到/注入该Impl类实例并调用其函数以获取片段引用。