【问题标题】:Show Fragment from Dynamic Feature Module in base (app) module?在基本(应用程序)模块中显示来自动态功能模块的片段?
【发布时间】:2020-08-12 02:36:42
【问题描述】:

在我的基本模块(应用程序)中,我有一些片段。我想将其中一个放在动态功能模块中,该模块将按需安装。在用户决定安装这个模块之前,我只会显示一个空的占位符而不是那个片段。我知道如果它是来自动态功能模块的 Activity,这很容易,但我真的需要在我的基本模块 Activity 中显示这个 Fragment。

这可能吗?

【问题讨论】:

    标签: android android-app-bundle dynamic-feature-module


    【解决方案1】:

    你可以用这种方式(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
        }
    }
    

    【讨论】:

    • 我认为你需要确保在 pro-guard 中为该类添加一个 keep 规则以避免混淆
    • 如果您的片段在模块内的某处代码中使用,则无需添加已由 proguard 保留的保留规则。如果它是模块内未使用的 Fragment,则必须这样做。
    【解决方案2】:

    要启用应用模块和功能模块之间的交互,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 module中创建一个对应的Impl。然后定位/注入这个 Impl 类实例并调用它的函数来获取片段引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-02
      • 1970-01-01
      • 1970-01-01
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      相关资源
      最近更新 更多