ViewModelProvider构造函数不接受片段继承类作为参数

时间:2020-01-26 19:22:49

标签: java android android-fragments constructor

我正在尝试制作一个片段,该片段将放置在与TabLayout交互的ViewPager中。但是,在实现MVVM时,在onCreate()函数上,我尝试为该片段创建一个ViewModel,但是由于它不接受Fragment作为构造函数的参数,因此我无法使用ViewModelProvider来这样做。这是代码:

package com.example.myfirstapp;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStoreOwner;

public class TabContaFragment extends Fragment {
    private static final String TAG = "TabConta";
    private MainViewModel pageViewModel;
    public TabContaFragment() {
        // Required empty public constructor
    }
    public static TabContaFragment newInstance() {
        return new TabContaFragment();
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pageViewModel = new ViewModelProvider(this).get(MainViewModel.class);
        pageViewModel.setIndex(TAG);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.tab_conta_fragment, container, false);
        return root;
    }
}

Android Studio给我这个错误:

Cannot resolve constructor ViewModelProvider(com.example.myfirstapp.TabContaFragment)

TabContaFragment继承了实现ViewModelStoreOwner的Fragment,使其成为ViewModelProvider构造函数的有效参数。但是,显然不是。

0 个答案:

没有答案