11

我正在使用新的拱门。来自谷歌的组件。

我在 Activity Login/Registering Fragments 中管理多亏了FragmentTransaction

Activity->RegisterFragment (with ViewPager) -> RegistrationSteps (adapter)

在 RegisterFragment 里面我有 ViewPager。我希望里面的所有页面ViewPager都使用相同的 ViewModel。

这些是注册步骤 ( RegistrationStepFragment),它采用父RegistrationFragment LifecycleOwner将ViewModel限定为它——我只是希望 ViewModel 被限定为这个父 Fragment。

RegistrationFragment.class继承自

public interface FragmentViewPagerListener<T extends LifecycleFragment> {
    void nextPage();
    T getLifecycleFragment();
}

继承自的注册步骤(页面)

public abstract class RegisterStepFragment extends LifecycleFragment {
    protected FragmentViewPagerListener mListener;
    protected RegisterViewModel mViewModel;

    public void setListener(FragmentViewPagerListener fragmentViewPagerListener) {
        this.mListener = fragmentViewPagerListener;
    }

    protected abstract void observeViewModel();

    @Override
    public void onCreated(@Nullable Bundle savedInstanceState) {
        super.onCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(mListener.getLifecycleFragment()).get(RegisterViewModel.class);
        observeViewModel();
    }

    protected abstract boolean validateData();
}

一切顺利,直到我到达 3 页,我想移回(到第二页)然后在mViewPager.setCurrentItem(1)(第 2 页:索引:1)中抛出异常

*java.lang.RuntimeException: Failed to call observer method
                                                                      at android.arch.lifecycle.ReflectiveGenericLifecycleObserver.invokeCallback(ReflectiveGenericLifecycleObserver.java:79)
                                                                      at android.arch.lifecycle.ReflectiveGenericLifecycleObserver.invokeMethodsForEvent(ReflectiveGenericLifecycleObserver.java:53)
                                                                      at android.arch.lifecycle.ReflectiveGenericLifecycleObserver.invokeCallbacks(ReflectiveGenericLifecycleObserver.java:61)
                                                                      at android.arch.lifecycle.ReflectiveGenericLifecycleObserver.onStateChanged(ReflectiveGenericLifecycleObserver.java:45)
                                                                      at android.arch.lifecycle.LifecycleRegistry$ObserverWithState.sync(LifecycleRegistry.java:209)
                                                                      at android.arch.lifecycle.LifecycleRegistry.handleLifecycleEvent(LifecycleRegistry.java:102)
                                                                      at android.arch.lifecycle.Li*fecycleDispatcher.dispatchIfLifecycleOwner(LifecycleDispatcher.java:150)

编辑

好的,我发现当移动到上一页时,片段被重新创建调用并mViewModel.observable()收到先前的成功消息并导致 viewpager 向前移动,这导致破坏刚刚创建的片段导致错误。

解决方案是创建仅在调用 post 时才发出值的SingleEventLiveData(如果值在观察者附加之前发生更改,则不要通知观察者)

我将其标记为关闭

4

0 回答 0