首页 > 解决方案 > 创建并显示来自另一个模块的片段

问题描述

我的 App 模块包含一个名为 Z 的库,但在 ZI 中需要创建并显示 App 中定义的 Fragment 的实例,我该怎么做?

BillingFragment我找到了这个,但问题是我在模块 Z 中时没有定义。

Class<?> class = Class.forName("example.package.BillingFragment");
Constructor<?> cons = class.getConstructor(BillingFragment.class);
BillingFragment object = (BillingFragment) cons.newInstance();

标签: javaandroidmodulecompilation

解决方案


如果您已经可以访问该片段并且您想使用公共默认无 arg 创建一个实例,constructor您可以调用:

Constructor constructor= BillingFragment.class.getConstructor();
BillingFragment fragment = (BillingFragment)constructor.newInstance();

甚至更好地使用公共静态newInstance方法:

Method method = BillingFragment.class.getMethod("newInstance", Class<?>... parameterTypes);
BillingFragment fragment = (BillingFragment) method.invoke(null, Object... args);

PS:您应该避免使用硬编码字符串,例如"example.package.BillingFragment"或如果应用程序被混淆"newInstance",这些字符串将变得无效。否则,如果您确实需要,请记住保留类和方法名称。proguard-rules


推荐阅读