我试图通过在一个抽象基类中移动一些ViewModel实例化来切割Dagger的一些样板文件,但找不到很好的方法来实现这一点.我的目的是从我的基本片段实例化我的所有ViewModel,以便它们可以被所有子片段使用,而不需要它们自己进行实例化.我的问题在于使用通用(VM)检索ViewModel,具体来说是:.get(viewModel::class.java).我还try 了.get(VM::class.java),这是不允许的

BaseFragment

abstract class BaseFragment<VM : ViewModel> : Fragment() {

    @Inject lateinit var viewModelFactory: ViewModelProvider.Factory
    lateinit var viewModel : VM

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        viewModel = ViewModelProviders.of(this, viewModelFactory).get(viewModel::class.java)
    }
}

ViewModelProviders.get(...) method signature

public <T extends ViewModel> T get(@NonNull Class<T> modelClass)

这有可能吗?

推荐答案

If you have a BaseFragment defined like this:

public class BaseFragment<T extends ViewModel> extends Fragment {

    @Inject
    protected T viewModel;

}

You can use the ViewModelUtils class from the Architecture Components's Github browser sample to create ViewModel factories.

/**
 * Creates a one off view model factory for the given view model instance.
 */
public class ViewModelUtil {
    private ViewModelUtil() {}
    public static <T extends ViewModel> ViewModelProvider.Factory createFor(T model) {
        return new ViewModelProvider.Factory() {
            @Override
            public <T extends ViewModel> T create(Class<T> modelClass) {
                if (modelClass.isAssignableFrom(model.getClass())) {
                    return (T) model;
                }
                throw new IllegalArgumentException("unexpected model class " + modelClass);
            }
        };
    }
}

In the onActivityCreated method of the BaseFragment you can add

    @Override
    public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ViewModelProvider.Factory viewModelFactory = ViewModelUtil.createFor(viewModel);
        ViewModelProviders.of(this, viewModelFactory).get(viewModel.getClass());
    }

这项技术的代码来自this blog post.

Kotlin相关问答推荐

使用Jackson反序列化HTML列表时出现MismatchedInputResponse

导入org.gradle.jvm.toolchain.internal.JavaToolchainFactory未解析引用:Java工具链工厂

在intellij中使用kotlin符号和floordiv

为什么在Spring中,对事务性方法调用的非事务方法调用仍然在事务中运行?

在Spring Boot应用程序中使用网络请求功能将关键字挂起作为冗余

禁用 Gradle执行消息

在 Kotlin 中将两个字节转换为 UIn16

jlink:在合并模块和 kotlin.stdlib 中打包 kotlin.*

Kotlin 中的密封和内部有什么区别?

如何判断给定字符串是否多次包含另一个子字符串?

T except one class

JobIntentService 被销毁,当应用程序被销毁时

如何从 Java 中隐藏 Kotlin 的 lateinit var 支持字段?

找不到 androidsdk.modules

API 'variant.getJavaCompile()' 已过时

如何用 kotlin 打包 List

用mockk验证属性设置程序吗?

API 26 上未显示 Android 通知

如何启用spring security kotlin DSL?

如何使用mockk库模拟android上下文