c0dehunter
c0dehunter

Reputation: 6150

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

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?

Upvotes: 4

Views: 1585

Answers (2)

Amritpal Singh
Amritpal Singh

Reputation: 1002

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.

Upvotes: 0

Công Hải
Công Hải

Reputation: 5241

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
    }
}

Upvotes: 5

Related Questions