在ViewModelProviders#of(Fragment)上键入错误 [英] Type error on ViewModelProviders#of(Fragment)

查看:53
本文介绍了在ViewModelProviders#of(Fragment)上键入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过有关构建良好ap体系结构的Google教程.我正在使用Java 8和SDK 26.这是我到目前为止的代码:

I'm trying to go through the google tutorial on building good ap architecture. I'm using java 8 and SDK 26. Here is the code I have so far :

package test.me;

import android.app.Fragment;
import android.arch.lifecycle.ViewModel;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;

public class ChronoFragment extends Fragment {

    private ViewModel my_model;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        my_model = ViewModelProviders.of(this).get(ViewModel.class);  // <-- error on this
        // and so on
    }
}

问题在于,到目前为止,SDK返回以下错误:

The trouble is that so far, the SDK returns the following error:

Cannot resolve the method 'of(test.me.ChronoFragment)'.

从那以后我不明白

  • ChronoFragment 的类型为Fragment
  • ViewModelProviders#of(Fragment)方法存在,并且可以通过sdk访问.
  • ChronoFragment is of type Fragment
  • The method ViewModelProviders#of(Fragment) does exist and is accessible via the sdk.

关于我在做什么错的任何想法吗?

Any idea on what I'm doing wrong ?

推荐答案

体系结构组件使用支持库中的appcompat Fragment ,而不是本机库.尝试将 Fragment 的导入更改为

Architecture Components uses the appcompat Fragment from the support library rather than the native one. Try changing your import for Fragment to

import android.support.v4.app.Fragment;

出于历史原因,有两个不同的 Fragment 类.它们具有相同的功能,但存在于两个不同的程序包中.有关详细信息,请参见为什么Android中有两个Fragment类?

For historical reasons, there are two different Fragment classes. They have the same functionality but exist in two different packages. For details, see Why are there two Fragment classes in Android?

截至2019年2月6日:

现在有第三个 Fragment 类.如果您使用的是新的AndroidX库,请执行

Now there is a third Fragment class. If you are using the new AndroidX libraries, then do

import androidx.fragment.app.Fragment;

请确保使用正确的 Fragment 类,该类与其余依赖项保持一致.

Be sure you use the correct Fragment class which is consistent with the rest of your dependencies.

这篇关于在ViewModelProviders#of(Fragment)上键入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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