我刚刚回到Java和Android世界。 在我寻找一个利用编译时间DI和MvvM的好项目启动器时,我找到了这两个:
现在我的问题...... 我想让基本活动看起来像这样(保留重要部分):
public abstract class ViewModelActivity<VM extends IViewModel> extends AppCompatActivity {
private ActivityComponent activityComponent;
@Inject
private VM viewModel;
protected void inject(AppComponent appComponent) {
appComponent.inject(this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppComponent appComponent = ((MvvmApplication) getApplication()).getAppComponent();
inject(appComponent);
activityComponent =
DaggerActivityComponent.builder()
.appComponent(appComponent)
.activityModule(new ActivityModule(this))
.build();
ViewModel.State savedViewModelState = null;
if (savedInstanceState != null) {
savedViewModelState = savedInstanceState.getParcelable(EXTRA_VIEW_MODEL_STATE);
}
viewModel = createViewModel(savedViewModelState);
}
}
所以我的AppComponent应该是这样的:
@AppScope
@Component(modules = {
AppContextModule.class,
AppModule.class,
NetworkModule.class,
GsonModule.class
})
public interface MyAppComponent extends AppComponent {
void inject(DashboardActivity baseActivity);
Picasso picasso();
}
AppComponent的位置:
@AppScope
public interface AppComponent {
Context appContext();
void inject(ViewModelActivity viewModelActivity);
}
最后具体的活动是:
public class DashboardActivity extends ViewModelActivity<DashboardViewModel> {}
现在我不断收到以下错误:
Error:(29, 10) error: activities.dashboard.DashboardViewModel cannot be
provided without an @Inject constructor or from an @Provides- or @Produces-
annotated method. This type supports members injection but cannot be
implicitly provided.
activities.dashboard.DashboardViewModel is injected at
mvvm.activity.ViewModelActivity.viewModel
activities.dashboard.DashboardActivity is injected at
app.inject(baseActivity)
我错过了什么?
谢谢!
答案 0 :(得分:1)
要使用带有匕首的MVVM,请查看来自Google的this sample code
它确实做得很好,它也使用了匕首的最新趋势,比如定义子模块和使用新的AndroidInjection
注入活动和片段。它还使用自定义工厂来创建视图模型,该模型负责注入构造函数字段。