【发布时间】:2018-06-08 00:07:53
【问题描述】:
我正在尝试学习 dagger 2,但我对使用接口注入构造函数感到困惑。这是我下面的代码:
MainActivity.java
public class MainActivity extends AppCompatActivity implements MainView {
// this keyword of request dependency . At compiling process, dagger will look at all of these annotations
//to create the exact dependency
@Inject MainPresenter mainPresenter ;
TextView textView ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textview) ;
DaggerPresenterComponent.create().inject(this);
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mainPresenter.doThings(8555) ;
}
});
}
/**********************************/
@Override
public void invokeRandomViewMethod(String msg) {
textView.setText(msg);
}
}
MainPresenter.java
public class MainPresenter {
private MainView mainView ;
@Inject
public MainPresenter(MainView mainView) {
this.mainView = mainView;
}
public void doThings(int value){
Random random = new Random();
int rand= random.nextInt(value) ;
if(mainView != null){
mainView.invokeRandomViewMethod("You random number is "+rand);
}
}
public interface MainView {
void invokeRandomViewMethod(String msg) ;
}
}
这是模块:
@Module
public class PresenterModule {
@Provides
// this is the method that will provide the dependancy
MainPresenter provideMainPresenter(MainView mainView){
return new MainPresenter(mainView);
}
}
这是组件
@Component (modules = PresenterModule.class)
public interface PresenterComponent {
void inject(MainActivity activity) ;
}
当我运行代码时,它显示了这个错误:
Error:(15, 10) 错误:com.imennmn.hellodagger2example.MainView 不能 在没有 @Provides-annotated 方法的情况下提供。 com.imennmn.hellodagger2example.MainView 被注入到 com.imennmn.hellodagger2example.presenterInjection.PresenterModule.provideMainPresenter(mainView) com.imennmn.hellodagger2example.MainPresenter 被注入 com.imennmn.hellodagger2example.MainActivity.mainPresenter com.imennmn.hellodagger2example.MainActivity 被注入 com.imennmn.hellodagger2example.simpleInjection.DataComponent.inject(activity)
我的问题是如何通过用匕首注入 MainView 并绑定 MainPresenter 和 MainActivity 来提供接口 MainView ? 任何帮助,将不胜感激 !
【问题讨论】:
标签: java android dependency-injection dagger-2 dagger