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

Anm*_*mol 9 android kotlin-android-extensions android-viewmodel android-jetpack androidx

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

因此要初始化viewmodel是否必须在onActivityCreated所有片段的

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

我正在浏览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>()
Run Code Online (Sandbox Code Playgroud)

所以我在gradle(app)中添加了以下依赖项:

    //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"
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试viewModels/activityViewModels在我的应用程序中使用它们的引用时,找不到。

我需要有关如何使用这些扩展名的一些基本示例的帮助,我尝试搜索一些未找到的示例。

Anm*_*mol 86

Atlast 我们有稳定版本。

搬到这里后,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"
    }
Run Code Online (Sandbox Code Playgroud)

参考

应用以上所有问题后,问题就解决了。

谢谢大家。


Bek*_*han 34

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

//ViewModels delegation extentensions for activity
implementation 'androidx.activity:activity-ktx:1.3.1'
Run Code Online (Sandbox Code Playgroud)

  • 是的,这是正确的答案。谢谢。 (2认同)

ONV*_*ETI 18

2024 年 2 月 15 日更新


你应该使用这个:

格罗维

dependencies {
    implementation "androidx.fragment:fragment-ktx:1.6.2"
}
Run Code Online (Sandbox Code Playgroud)

科特林 KTS

dependencies {
    implementation("androidx.fragment:fragment-ktx:1.6.2")
}
Run Code Online (Sandbox Code Playgroud)

更多信息:

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

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


小智 5

尝试

implementation 'androidx.fragment:fragment-ktx:1.1.0-beta02'
Run Code Online (Sandbox Code Playgroud)

  • @DenysMakhov 错了。`fragment-ktx` 适用于 Activity 和 Fragment。 (4认同)
  • 在 Activity 中使用“by viewModels()”就足够了,因为您已经在 Activity 中,如果您需要片段中 Activity 的视图模型,请使用“by ActivityViewModels()” (3认同)
  • @IgorGanapolsky只能从Fragment调用此委托。但是,如果在实现中添加“ androidx.activity:activity-ktx:1.0.0”依赖关系,则可以为Activity使用类似的委托。 (2认同)
  • @Anmol 答案中的版本最近升级到稳定版。对于“by ViewModels()”,您至少需要处于 1.1.0 版本 (2认同)