如何在AndroidX中实例化ViewModel? [英] how to instantiate ViewModel In AndroidX?

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

问题描述

我想使用androidx库在Activity中初始化ViewModel

I want to initialize ViewModel in Activity using androidx library

我已经尝试了文档中所说的内容,但是没有用. ".of"无法解析.

I have tried what documentation says but it is not working. the ".of" is not resolved.

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProvider import com.example.myapplication.databinding.ActivityMainBinding

import android.os.Bundle import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProvider import com.example.myapplication.databinding.ActivityMainBinding

MainActivity类:AppCompatActivity(){

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val binding: ActivityMainBinding = DataBindingUtil.setContentView(
        this, R.layout.activity_main)
    binding.setLifecycleOwner(this)

    var model = ViewModelProvider.of(this).get(SheduleViewModel::class.java)

}

}

of尚未解决,可能还有其他方法可以在androidx中实现

of is not resolved, may be there are other way to do it in androidx

推荐答案

更新后的答案:

事情发生了一些变化,因为以前需要依赖-ViewModelProviders-已弃用(有关详细信息,请参见旧答案).现在,您可以直接使用ViewModelProvider构造函数.

Things changed a little bit, as the previously needed dependency - ViewModelProviders - got deprecated (see the old answer for details). You can now use the ViewModelProvider constructor directly.

因此,在这种情况下,答案将是:

So, in this case, the answer would be:

private val viewModel = ViewModelProvider(this).get(SheduleViewModel::class.java)

请注意,但是,如果要在Fragment中实例化ViewModel,则可以添加androidx.fragment:fragment-ktx:$Version依赖项,然后利用属性委派:

Note that, however, if you're instantiating a ViewModel in a Fragment, you can add the androidx.fragment:fragment-ktx:$Version dependency and then make use of property delegation:

private val viewModel: SheduleViewModel by viewModels()

内部将使用ViewModelProvider并将您的ViewModel范围限定为您的Fragment.这只是写同一件事的一种更简洁的方式.

Which internally will use ViewModelProvider and scope your ViewModel to your Fragment. It's just a more concise way of writing the same thing.

ViewModelProvider构造函数和by viewModels()都接受工厂作为参数(用于注入ViewModel):

Both the ViewModelProvider constructor and by viewModels() also accept a factory as a parameter (useful for injecting your ViewModel):

private val viewModel = 
    ViewModelProvider(this, viewModelFactory).get(SheduleViewModel::class.java)

private val viewModel: SheduleViewModel by viewModels { viewModelFactory }

使用最适合您的一种.

旧答案:

添加androidx.lifecycle:lifecycle-extensions:$lifecycleExtensionsVersion依赖项以导入ViewModelProviders.

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

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