我正在使用新的拱门。来自谷歌的组件。
我在活动登录/注册由于FragmentTransaction
Activity->RegisterFragment (with ViewPager) -> RegistrationSteps (adapter)
在RegisterFragment里面我有ViewPager。
我希望ViewPager
内的所有页面都使用相同的ViewModel。
这些是注册步骤(RegistrationStepFragment
),它将带有 ViewModel 的父RegistrationFragment
LifecycleOwner 带到它 - 我只是想让ViewModel成为范围到这个父片段。
RegistrationFragment.class 来自
public interface FragmentViewPagerListener<T extends LifecycleFragment> {
void nextPage();
T getLifecycleFragment();
}
RegistartionSteps(页面)来自
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)
修改
好的,我发现在转到上一页时,Fragment被重新处理,而mViewModel.observable()
收到了之前的 SUCCESS 消息并导致了viewpager向前移动,导致破坏刚刚创建的片段导致错误的原因。
解决方法是创建仅在调用post时才发出值的SingleEventLiveData(如果在附加观察者之前值已更改,则不通知观察者)
我将其标记为CLOSE