如何通过viewModels获取viewModel? (片段-ktx)

问题描述 投票:0回答:13

我正在为 Activity 及其所有片段使用 Single viewModel。

所以要初始化

viewmodel
,如果必须在所有片段的
onActivityCreated
中编写此设置代码

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProviders.of(activity!!).get(NoteViewModel::class.java)
    }

我正在彻底浏览 Android KTX 扩展页面:(请参阅此处

我发现我可以像这样初始化视图模型:

    // Get a reference to the ViewModel scoped to this Fragment
    val viewModel by viewModels<MyViewModel>()

    // Get a reference to the ViewModel scoped to its Activity
    val viewModel by activityViewModels<MyViewModel>()

所以我将以下依赖项添加到我的 gradle(应用程序)中:

    //ktx android
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.fragment:fragment-ktx:1.0.0'
    implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"

但是当我尝试在我的应用程序中使用

viewModels/activityViewModels
时,找不到它们的参考。

我需要有关如何使用这些扩展程序和一些基本示例的帮助,我尝试搜索示例但没有找到任何示例。

android androidx android-jetpack kotlin-android-extensions android-viewmodel
13个回答
116
投票

我们终于有了稳定版本。

搬到

implementation 'androidx.fragment:fragment-ktx:1.1.0'
后,我遇到了另一个问题。

编译器错误:

无法将使用 JVM 目标 1.8 构建的字节码内联到以下字节码中 使用 JVM 目标 1.6 构建

build.gradle
(模块
:app

compileOptions {
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
}

kotlinOptions {
    jvmTarget = "1.8"
}

参考

应用上述所有内容后,问题已解决。


67
投票

尝试

implementation 'androidx.fragment:fragment-ktx:1.1.0-beta02'

2021 更新

这不再是测试版。它适用于撰写本文时的最新稳定版本。您还需要将其导入片段的 Kotlin 文件中。

implementation 'androidx.fragment:fragment-ktx:1.3.2'
import androidx.fragment.app.activityViewModels

32
投票

我认为如果你想将 kotlin 委托用于视图模型,你的活动需要具有这种依赖关系

//ViewModels delegation extentensions for activity
implementation 'androidx.activity:activity-ktx:1.3.1'

15
投票

2023 年 9 月 14 日更新


你应该使用这个:

格罗维

dependencies {
    implementation "androidx.fragment:fragment-ktx:1.6.1"
}

科特林 KTS

dependencies {
    implementation("androidx.fragment:fragment-ktx:1.6.1")
}

更多信息:

  1. https://developer.android.com/kotlin/ktx#fragment

  2. https://developer.android.com/topic/libraries/architecture/viewmodel#implement


3
投票

您使用的是最新的 alpha 版本:

dependencies {
    implementation 'androidx.fragment:fragment-ktx:1.2.0-alpha01'
}

3
投票

注意:这也适用于 Jetpack Compose

此处

复制依赖项

目前

2021 June 5
依赖如下:

dependencies {
    val activity_version = "1.2.3"

    // Java language implementation
    implementation("androidx.activity:activity:$activity_version")
    // Kotlin
    implementation("androidx.activity:activity-ktx:$activity_version")
}

3
投票

对于googlers:你的Activity应该继承AppCompatActivity,而不是Activity


3
投票

如果您收到找不到设置器的错误,请务必对您的

ViewModel
属性使用
val
而不是 var


2
投票

在版本1.1.0-alpha03中添加了扩展函数viewModels(...)。因此,为了在您的应用程序中使用它,您必须实现与 1.1.0-alpah03 或更高版本匹配的版本的fragment-ktx。

我刚刚发现这一点,所以我求助于使用版本 1.1.0-rc01 因为我不想使用 alpha/beta 版本。


2
投票

您可以实施

implementation 'androidx.fragment:fragment-ktx:1.1.0'

其实KTX包中的BY viewModels实现是这样的,你不妨自己实现一个扩展功能

@MainThread
inline fun <reified VM : ViewModel> ComponentActivity.viewModels(
        noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
): Lazy<VM> {
    val factoryPromise = factoryProducer ?: {
        val application = application ?: throw IllegalArgumentException(
                "ViewModel can be accessed only when Activity is attached"
        )
        ViewModelProvider.AndroidViewModelFactory.getInstance(application)
    }

    return ViewModelLazy(VM::class, { viewModelStore }, factoryPromise)
}

1
投票

试试这个。它对我有用。

implementation "androidx.fragment:fragment-ktx:1.2.5"

1
投票

您可以通过像这样实现

fragment-ktx
库来修复它

def fragment_version = "1.4.0"

implementation("androidx.fragment:fragment-ktx:$fragment_version")

查看更多并查看最新版本这里


-5
投票

如果您来这里寻找 Koin 的解决方案

请注意,您可以使用 Koin 来完成此工作:

private val viewModel by viewModel<NoteViewModel>()

将使用导入

import org.koin.android.viewmodel.ext.android.viewModel

来自依赖:

implementation "org.koin:koin-android-viewmodel:+"
// 将 + 更改为 w/e 是您阅读本文时最新的内容

© www.soinside.com 2019 - 2024. All rights reserved.