1提供新的Android喷油器创建范围
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Scope;
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface BaseScope {
}
2 - 创建您的合同
public interface FeatureContract {
interface View {
void onReceiveError(Throwable throwable);
void onReceiveItems(List<Object> items);
void showAlertDialog();
... //others methods
}
interface Presenter {
void onInitView(Object item);
}
}
3-创建模块(dagger2)
import dagger.Module;
import dagger.Provides;
@Module
public class FeatureContractModule {
private final FeatureContract.View mView;
public FeatureContractModule(FeatureContract.View view) {
mView = view;
}
@Provides @BaseScope
FeatureContract.Presenter providesFeaturePresenter(FeatureContract.View view) {
return new FeaturePresenter(view);
}
@Provides @BaseScope
FeatureContract.View providesFeatureView() {
return mView;
}
}
4-创建您的演示者
public class FeaturePresenter implements FeatureContract.Presenter{
@NonNull
private final FeatureContract.View mView;
public FeaturePresenter(@NonNull FeatureContract.View view){
mView = view;
}
@Override
public void onInitView(Object item){
mView.showAlertDialog(); //<--for sample
}
}
5在你的片段
import javax.inject.Inject;
public class FeatureFragment extends Fragment implements FeatureContract.View{
@Inject FeatureContract.Presenter mPresenter;
@Override public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((MyApplication) getActivity().getApplication()).getDataComponent()
.plus(new FeatureContractModule(this /*view*/))
.inject(this /*fragment*/);
mPresenter. onInitView(null);
}
}
5-你的应用
public class MyApplication extends Application {
//Dagger object
private DataComponent mDataComponent;
/**
* Dagger Injector
*/
public static DataComponent get(Context context) {
MyApplication application = (MyApplication) context.getApplicationContext();
return application.mDataComponent;
}
@Override
public void onCreate() {
super.onCreate();
mDataComponent = DaggerDataComponent.builder()
.dataModule(new DataModule(this, Locale.getDefault()))
.build();
}
public DataComponent getDataComponent() {
return mDataComponent;
}
}
6 - 创建DataComponent
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {DataModule.class})
public interface DataComponent {
Application application();
FeatureComponent plus(FeatureContractModule module);
...
}
7 - 最后的ComponentModule
import dagger.Module;
import dagger.Provides;
@BaseScope
@Subcomponent(modules = FeatureContractModule.class)
public interface FeatureComponent {
void inject(FeatureFragment fragment);
}
我相信我还没有忘记任何东西
的可能重复的构造函数添加
@Inject
[我如何解决Dagger 2错误'...不能提供\ [... \]'?](https://stackoverflow.com/questions/44912080/how-doi-i-fix-dagger-2-错误 - 不能提供) –这个解决方案不适合你吗? https://stackoverflow.com/questions/36838898/presenter-injection-with-dagger-2?answertab=votes#tab-top –
@MaximeJallu - 不,我已检查所有注释,我使用新的android注射器提供Dagger2 – Passiondroid