4

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?

c0dehunter
  • 6,412
  • 16
  • 77
  • 139

2 Answers2

5

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
    }
}
Công Hải
  • 4,961
  • 3
  • 14
  • 20
  • 1
    I think you need to make sure to add a keep rule in pro-guard for that class to avoid obfuscation – Ahmed na Feb 24 '21 at 01:22
  • If your fragment is used in somewhere code inside module you don't need to add keep rule it already keeps by proguard. If it's an unused Fragment inside the module you have to do it. – Công Hải Feb 24 '21 at 02:21
  • This didn't work for me when I uploaded to play store. I get a crash `Caused by: java.lang.ClassNotFoundException: com.myapp.customviewdynamicfeature.CustomFragment` – VIN Mar 25 '22 at 19:28
  • did you build APK or AAB? – Công Hải Mar 27 '22 at 08:48
0

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.

Amritpal Singh
  • 984
  • 2
  • 14
  • 33
  • I have a feature module that is dependent on the app module, I can access :app module resources, but I need to open a fragment of :feature module, as I cannot access :feature module for circular dependency, how can I do it? – Mahbub Munna Jun 07 '22 at 08:25