Show Fragment from Dynamic Feature Module in base (app) module?

Viewed 1018

In my base module (app) I have a few Fragments. I would like to put one of them in a Dynamic Feature Module, which would get installed on-demand. Until the user decides to install this module, I would just show an empty placeholder instead of that Fragment. I know it's easy if it's an Activity from Dynamic Feature Module, but I would really need to show this Fragment in my base module Activity.

Is this possible?

2 Answers

You can use this way (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
    }
}

To enable interaction between the app module and feature modules, one can use dependency injection or service locator pattern. The app can locate the feature module's implementation class and invokes its public API which returns the fragment instance in the app module and load that in main Activity's container.

for ex: create a Feature interface in app and corresponding Impl in feature module. Then locate/inject this Impl class instance and invoke its function to get the fragment reference.

Related