问题
I have two flavors: pro and free. In each of these, I have a MainActivity, but I want the MainComponent
and MainModule
to be the same for both, so MainComponent
and MainModule
are both in src/java/main, but I get an error in my MainComponent due to not having an import of MainActivity of both flavors. Here, let me make it clear:
Here's what the MainComponent
in src/java/main looks like:
import com.xxx.myapp.di.modules.MainModule;
import com.xxx.myapp.free.MainActivity;
import com.xxx.myapp.presenters.MainPresenterImpl;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {MainModule.class})
public interface MainComponent {
void inject(MainActivity mainActivity);
void inject(MainPresenterImpl mainPresenter);
}
In the code shown above, it only imports the MainActivity
from the free flavor, hence giving an error when I switch to the pro flavor.
回答1:
When using flavors you should not have different packages for the different components.
Instead of com.xxx.myapp.free.MainActivity
Move MainActivity up a level to com.xxx.myapp.MainActivity
both versions of MainActivity must have the same fully qualified named.
UPDATE
You have two classes named MainActivity
but to Java they have different fully qualified names com.xxx.myapp.free.MainActivity
and com.xxx.myapp.pro.MainActivity
(just a guess).
What you really need is one class com.xxx.myapp.MainActivity
with flavor specific implementations. YOu can add a separate implementation of MainActivity to each flavor by the flavor specific folder paths.
app/src/free/java/com/xxx/myapp/MainActivity.java
app/src/pro/java/com/xxx/myapp/MainActivity.java
Gradle will only compile the implementation for the selected flavor.
回答2:
You can determine the flavor at runtime by using BuildConfig.FLAVOR and from there you can selectively add advertisements and what not. I would personally do it this way.
来源:https://stackoverflow.com/questions/34046289/share-a-dagger-2-component-between-two-different-flavors