viewModels 扩展方法在 androidx.activity:activity-ktx 库中
gradle 中添加如下依赖
implementation "androidx.activity:activity-ktx:1.4.0"
implementation "androidx.fragment:fragment-ktx:1.4.1"
敲重点!!! 如果还是找不到,需查看当前 activity 继承的是谁,必须是 androidx.activity.ComponentActivity
viewModels 方法源码如下
package androidx.activity
import androidx.annotation.MainThread
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelLazy
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.Factory
/**
* Returns a [Lazy] delegate to access the ComponentActivity's ViewModel, if [factoryProducer]
* is specified then [ViewModelProvider.Factory] returned by it will be used
* to create [ViewModel] first time.
*
* ```
* class MyComponentActivity : ComponentActivity() {
* val viewmodel: MyViewModel by viewModels()
* }
* ```
*
* This property can be accessed only after the Activity is attached to the Application,
* and access prior to that will result in IllegalArgumentException.
*/
@MainThread
public inline fun <reified VM : ViewModel> ComponentActivity.viewModels(
noinline factoryProducer: (() -> Factory)? = null
): Lazy<VM> {
val factoryPromise = factoryProducer ?: {
defaultViewModelProviderFactory
}
return ViewModelLazy(VM::class, { viewModelStore }, factoryPromise)
}
可以看到该方法扩展的是 androidx.activity.ComponentActivity