我是Android开发的新手,所以我的问题可能很奇怪,甚至不可能。我不知道!
无论如何,我正在构建具有大量共享元素的多个应用程序,因此我决定使用这些组件构建一个库并在所有应用程序中使用它,而不是愚蠢的复制和粘贴代码。 例如,该库处理欢迎屏幕和登录/注册流程活动等。因此,此方法可能会导致以下问题:
所以我的问题实际上可以归结为三个部分:
答案 0 :(得分:2)
- 无论如何,我是否可以将此信息从应用程序传递到图书馆? 我可以以某种方式修改库的R类吗?或者我可以使用 库中应用的R类?我也可以称这部分 库作为传递我需要的参数的函数。但是第一个 解决方案对我来说可能看起来更干净?
您不需要修改R类,因为可以通过创建具有相同名称的文件来覆盖资源文件。但这不是一个干净的解决方案,因为您经常需要确保您的项目和库资源名称相同。
- 无论Q1的答案是什么。我将在哪里以及如何执行此操作?的 图书馆本身有欢迎活动,应该是 应用中的第一个活动。应用一旦完成,我将如何以及在何处执行此操作 开始并且在第一个活动开始之前?
与其覆盖资源名称,不如修改它的库以接受使用该库的合同配置。这里是示例:
首先,创建用于保存配置的类:
public class Configuration {
private int welcomeImageDrawableId;
private int logoDrawableId;
// constructor
public Configuration(int welcomeImageDrawableId, int logoDrawableId) {
this.welcomeImageDrawableId = welcomeImageDrawableId;
this.logoDrawableId = logoDrawableId;
}
// setter and getter.
public int getLogoDrawableId() {
return logoDrawableId;
}
}
第二,通过创建 Singleton 类将库的配置类用于库内部:
public class MyLibrary {
private static MyLibrary myLibrary;
private Configuration configuration;
private MyLibrary(){}
private MyLibrary(Configuration configuration) {
this.configuration = configuration;
}
public static MyLibrary getInstance() {
if(myLibrary == null) {
throw new RuntimeException("Need call createInstanceWith method first!!");
}
return myLibrary;
}
public static MyLibrary createInstanceWith(Configuration configuration) {
if(myLibrary == null) {
synchronized(MyLibrary.class) {
if (myLibrary == null) {
myLibrary = new MyLibrary(configuration);
}
}
}
return test;
}
public Configuration getConfiguration() {
return configuration;
}
}
第三,通过单例类在您的库中使用配置类。像这样的东西:
// assume imvLogo is an existing ImageView
Configuration configuration = MyLibrary.getInstance().getConfiguration();
imvLogo.setImageResource(configuration.getLogoDrawableId());
最后,将库与以下资源一起使用时注册合同:
Configuration configuration = new Configuration(R.drawable.welcome, R.drawable.logo);
MyLibrary.createInstanceWith(configuration);
注意:所有代码尚未经过测试,预计会出现错误。
答案 1 :(得分:0)
除了上述解决方案,我还找到了另一种无需初始化库即可实现整个目标的方法。 我认为正确的方法是在库中使用productFlavors。这使库可以共享一个主要的源代码集,一个主要的资源集,然后针对每个应用程序/风味共享另外的资源集。这对我而言已经足够。
有关构建变体和风味的更多信息: https://developer.android.com/studio/build/build-variants