gpt4 book ai didi

java - 无法解析 ViewModelProviders 中 android.support.v4.app.FragmentActivity 的方法

转载 作者:行者123 更新时间:2023-12-02 10:12:38 26 4
gpt4 key购买 nike

我正在尝试在我的应用程序中实现架构组件,但是当我使用 getActivity() 将生命周期所有者添加到 fragment 内的 View 模型时,其显示消息

Cannot resolve method of android.support.v4.app.FragmentActivity

这是我的代码:

 viewModel = ViewModelProviders.of(getActivity()).get(MyViewModel.class);
viewModel.setToken(token);
viewModel.getRecent().observe(getActivity(), new Observer<List<Recent>>() {
@Override
public void onChanged(List<Recent> recent) {
adapter.setData(recent);
}
});

我的 fragment 源自android.support.v4.app.Fragment

并且 MyActivity 扩展了 AppCompatActivity

这是我的 Gradle 文件:

    def paging_version = "2.1.0"
def lifecycle_version = "2.0.0"
def room_version = "2.1.0-alpha04"

implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
implementation "androidx.paging:paging-runtime:$paging_version"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

如何解决这个问题?提前致谢。

最佳答案

问题

androidx.lifecycle.ViewModelProviders.of(FragmentActivity)中,它们接受androidx.fragment.app.FragmentActivity,而不是android.support.v4.app .FragmentActivity.

解决方案

  1. 使用 Android Studio 3.2 引入的 Migrate to AndroidX 将整个项目迁移到 AndroidX。您可以在this page中找到信息
  2. 更改依赖项版本以支持库版本。可以找到依赖项版本 this page
dependencies {
def lifecycle_version = "1.1.1"

// ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:$lifecycle_version"
// alternatively - just ViewModel
implementation "android.arch.lifecycle:viewmodel:$lifecycle_version" // For Kotlin use viewmodel-ktx
// alternatively - just LiveData
implementation "android.arch.lifecycle:livedata:$lifecycle_version"
// alternatively - Lifecycles only (no ViewModel or LiveData).
// Support library depends on this lightweight import
implementation "android.arch.lifecycle:runtime:$lifecycle_version"

annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version" // For Kotlin use kapt instead of annotationProcessor
// alternately - if using Java8, use the following instead of compiler
implementation "android.arch.lifecycle:common-java8:$lifecycle_version"

// optional - ReactiveStreams support for LiveData
implementation "android.arch.lifecycle:reactivestreams:$lifecycle_version"

// optional - Test helpers for LiveData
testImplementation "android.arch.core:core-testing:$lifecycle_version"
}

关于java - 无法解析 ViewModelProviders 中 android.support.v4.app.FragmentActivity 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54896835/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com