所以我一直在学习Dagger 2 Android,但我遇到了问题。我想在运行时传递值。我读过很多博客等,但是找不到任何解决方案。每个Dagger来源都是关于Dagger 2而不是Dagger 2 Android。无论如何,在Dagger 2 Android上也可以做到吗?还是我应该简单地迁移到Dagger 2?
这是AppComponent.java
@Singleton
@Component(
modules = {
AndroidSupportInjectionModule.class,
ActivityBuildersModule.class,
AppModule.class,
}
)
public interface AppComponent extends AndroidInjector<BaseApplication> {
@Component.Builder
interface Builder{
@BindsInstance
Builder application(Application application);
AppComponent build();
}
}
这是ActivityBuildersModule.java
@Module
public abstract class ActivityBuildersModule {
//For injection class
@AuthScope
@ContributesAndroidInjector(
modules = {
AuthModule.class,
InjectFragmentBuildersModule.class, //Only gonna exist on AuthActivity Scope
MainViewModelsModule.class,
})
abstract AuthActivity contributeAuthActivity();
}
这是AuthModule.java
@Module
public class AuthModule {
//SubComponent
@AuthScope
@Provides
static Tiers getTiers(){
return new Tiers();
}
@AuthScope
@Provides
static Engine getEngine(){
return new Engine();
}
@AuthScope
@Provides
static Car getCar(Tiers tiers, Engine engine, @Named("String1")String string){
return new Car(tiers,engine,string);
}
@AuthScope
@Provides
static FragmentManager getFragmentManager(AuthActivity authActivity){
return authActivity.getSupportFragmentManager();
}
}
最后是AuthActivity.java
public class AuthActivity extends DaggerAppCompatActivity {
private static final String TAG = "AuthActivity";
@Inject
Car car;
@Inject
@Named("String1")
String test1;
@Inject
@Named("String2")
String test2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auth);
car.startCar();
car.setmBrand("new test brand");
NavController navController= Navigation.findNavController(this,R.id.nav_host_fragment);
navController.navigate(R.id.injectFragment);
}
}
所以可以说我想将一些字符串传递给Car而不是@Named(“ String1”)怎么办?我用二传手解决了这个问题,但我无法每次都解决那样的问题。