0

我刚刚回到 Java&Android 世界。在我寻找一个可以利用编译时间 DI 和 MvvM 的好的项目启动器时,我发现了这两个:

  1. 编写可测试的 Android MVVM
  2. 国家 - 一个示例 Android 应用

现在我的问题......我想让一个基本活动看起来像这样(保留重要部分):

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)

我错过了什么?

谢谢!

4

1 回答 1

0

要将 MVVM 与 dagger 一起使用,请查看google的此示例代码

它确实做得很好,它也使用了 dagger 的最新趋势,比如定义子模块和使用 newAndroidInjection来注入活动和片段。它还使用自定义工厂来创建负责注入构造函数字段的视图模型。

于 2018-02-16T21:18:19.963 回答