我正在尝试实例化一个ViewModel以在所有片段中使用,以更新所有可见的片段recyclerview,但是我得到的是这个后续错误ReleasesViewModel releasesViewModel = ReleasesViewModel.of(this).get(ReleasesViewModel.class);
of
方法无法解析。
public class UpcomingViewPagerFragment extends Fragment implements Observable {
private static final String TAG = UpcomingGamesFragment.class.getSimpleName();
public ViewPager mViewPager;
private List<Observer> mObserversList = new ArrayList<>();
private SectionsPagerAdapter mSectionsPagerAdapter;
public UpcomingViewPagerFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_upcoming_view_pager, container, false);
// Viewpager
mViewPager = view.findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(3);
// Get the ViewModel
ReleasesViewModel releasesViewModel = ReleasesViewModel.of(this).get(ReleasesViewModel.class);
为清楚起见,省略了代码。
我的两个片段都为android.support.v4.app.Fragment
。
这是我的viewmodel livedata类
public class ReleasesViewModel extends ViewModel {
private MutableLiveData<List<UpcomingGamesFragment>> upcomingFragmentLiveData =
new MutableLiveData<>();
public ReleasesViewModel() {
}
public LiveData<List<UpcomingGamesFragment>> getUpcomingFragmentList() {
return upcomingFragmentLiveData;
}
}
答案 0 :(得分:0)
您的of
实现中没有方法ViewModel
,因为该方法来自ViewModelProviders
类;-)
因此,请更改以下代码:
ReleasesViewModel releasesViewModel = ReleasesViewModel.of(this).get(ReleasesViewModel.class);
收件人:
ReleasesViewModel releasesViewModel = ViewModelProviders.of(this).get(ReleasesViewModel.class);
这应该可以解决问题。
有关更多信息,请参见:https://developer.android.com/topic/libraries/architecture/viewmodel。