我在我的项目中使用dagger2。项目遵循MVP模式。我的应用程序设计就像我正在使用单个活动 通过我的申请。所有UI元素都在片段中,单个活动充当片段 项目中所有片段的主机活动。我项目中的每个模块都将使用 片段作为UI组件,如LoginFragment,SplashScreenFragment,RegistrationFragment,HomeScreenFragment。
所以基本上我的活动只会启动一次,它只包含一个片段容器,片段将被替换 当用户导航到每个模块中的每个屏幕时。
每次用户从一个屏幕移动到另一个屏幕,而不是创建活动时,它只会调用gotoNextScreen
在活动中,然后将膨胀下一个片段
所以我的活动只会进行以下操作
由于我有n
个屏幕(n
个数量的片段和演示者),我无法使用字段
注入像
public class MainActivity{
@Inject RegistrationFragment registrationFragment;
@Inject LoginFragment loginFragment
}
因为字段数量很大,同时我们只需要一个片段 和一位主持人。所以我做的是,我为每个模块创建了单独的组件, 使其成为我的主要App组件的依赖组件。现在我的活动看起来像这样。
public void gotoNextScreen(ScreenType screentype, Data data){
switch(screentype){
case LOGIN:
DaggerLoginComponent.builder()
.appComponent(mAppComponent)
.build();
// get login fragment and presenter from login component and inflate
break;
case REGISTRATION:
DaggerLoginComponent.builder()
.appComponent(mAppComponent)
.build();
// get registration fragment and presenter from registration component and inflate
// and the switch case goes on like this
}
}
我发现它非常困难,因为我几乎在每个模块中重复代码。 我正在为不同的fragmet类型和演示者创建不同的组件。
我可以简化使用泛型或类似的东西吗?匕首是否提供任何简单的方法来解决这种问题 问题?任何人都可以展示一些示例代码来解决这个问题吗?
答案 0 :(得分:1)
我不知道这是否是正确的方法,因为我对Dagger2和MVP也是新手,但我已经实现了它:
Fragment有一个回调活动,如official documentation中所述。
作为gotoNextScreen
方法的回调。
goToNextScreen
(由Activity实现)调用Activity presenter。
此演示者负责实例化片段并在视图(活动)上调用displayFragment
方法。就像那样,Activity对实现一无所知。它只是将信息传递给演示者,然后显示片段。
看起来像那样:
<强> FragmentA 强>
public void onNext(){
mActivityCallback.gotoNextScreen(screentype, data);
}
活动
public void gotoNextScreen(ScreenType screentype, Data data){
mPresenter.goToNext(screentype, data);
}
public void displayFragment(Fragment f){
// Code to replace the current Fragment by the fragment f
}
活动主持人
public void goToNext(ScreenType screentype, Data data){
Fragment f;
switch(screentype){
case A:
f = FragmentA.newInstance(data);
break;
case B:
f = FragmentB.newInstance(data);
break;
...
}
mView.displayFragment(f); // mView is the Activity
}
正如我所说,我不确定这个实现是否有效:
gotoNextScreen
方法(在“活动和演示者”中)修改强>
匕首部分:
创建时注入活动:
MainActivityComponent component = ((CustomApplication) getApplication()).getComponent()
.plus(new MainActivityModule());
与片段相同:
活动的回调有getComponent
方法,当附加片段时,它会调用:
public void onAttach(Context context) {
//...
activityCallback.getComponent().inject(FragmentA.this)
}