无法在Activity中实例化ViewModel [英] ViewModel cannot be instantiated in an Activity

查看:63
本文介绍了无法在Activity中实例化ViewModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实例化一个ViewModel以便在我的所有Activity中使用.

I am trying to instantiate one ViewModel to use across all of my Activity(s).

public class LaunchActivity extends Activity {
    private Controller control;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_launch);
         control = ViewModelProviders.of(this).get(Controller.class);
    }
}

但是在 control = ViewModelProviders.of(this)<-时出现错误,指出它无法解析 of(this),但基于示例Android开发人员在实现ViewModel的此处;扩展ViewModel的类应该可以在Activity上实例化,对吗?

but I got an error at control = ViewModelProviders.of(this) <-- stating that it cannot resolve of(this), but based on the example here by Android Developer on Implementing ViewModel; a class that extends ViewModel should be able to be instantiated on Activity, am I right?

如果我在做什么是错误的,我应该如何为我的Activity实例化一个ViewModel对象?因为 ViewModelProviders.of()仅适用于Fragment,我是否必须用Fragment创建 n 个活动?

If what I am doing is wrong, how should I instantiate a ViewModel object for my Activity(s)? Do I have to create n number of Activity(s) with Fragment(s) since ViewModelProviders.of() only works with Fragment?

推荐答案

您需要使用支持库活动.

AppCompatActivity FragmentActivity

这篇关于无法在Activity中实例化ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆