【发布时间】:2016-10-28 05:30:33
【问题描述】:
正如我之前读到的,dagger 会发出所有构造函数并自己提供它们,所以我们的业务中几乎不应该有任何构造函数,现在想象在 Fragment 和 Activity 中有一个 RecyclerView正在注入片段,我如何为片段注入LayoutManager 和Adapter 以及Presenter(不将它们注入到活动中并通过参数传递给片段)
我正在处理的示例是here,但他根据MVP 模式将Activity 本身用作View,但我试图改用Fragment。
This 是他的Activity(这里注入了recycler view 和presenter)。
我的代码:
UserComponent 是 AppComponent 的子组件
@UserScope
@Subcomponent(modules = UserModule.class)
public interface UserComponent {
RepoListComponent plus(RepoListModule repoListModule);
UserEntity getUserEntity();
}
RepoListModule:
@Module
public class RepoListModule {
private RepoListContract.View view;
public RepoListModule(RepoListContract.View view) {
this.view = view;
}
@Provides
RepoListContract.View provideRepoListContractView(){
return view;
}
@Provides
LinearLayoutManager provideLayoutManager(Context context) {
return new LinearLayoutManager(context);
}
@Provides
RepoListAdapter provideAdapter(RepoListContract.View view) {
return new RepoListAdapter(view);
}
}
RepoListComponent:
@Subcomponent(modules = RepoListModule.class)
public interface RepoListComponent {
void inject(RepoListContract.View view);
}
RepoListActivity:
public class RepoListActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_repo_list);
RepoListFragment fragment = (RepoListFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = new RepoListFragment();
ActivityUtils.addFragmentToActivity(getSupportFragmentManager(),
fragment, R.id.fragment_container);
}
GApplication.get(getApplicationContext())
.getUserComponent().plus(new RepoListModule(fragment))
.inject(fragment);
}
}
RepoListFragment:
public class RepoListFragment extends Fragment implements RepoListContract.View {
@BindView(R.id.rv_repo) RecyclerView rvRepo;
@Inject RepoListContract.Presenter presenter;
@Inject LinearLayoutManager layoutManager;
@Inject RepoListAdapter adapter;
public static RepoListFragment newInstance() {
return new RepoListFragment();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_repo_list, container, false);
ButterKnife.bind(this, v);
initRvRepo();
return v;
}
private void initRvRepo() {
rvRepo.setLayoutManager(layoutManager); // null
rvRepo.setAdapter(adapter); //null
}
@Override
public void onResume() {
super.onResume();
presenter.subscribe(); //NullPointerException
}
}
【问题讨论】: