当我们执行popBackStack
并返回后一堆栈中的前一个片段时,方法onViewCreated(View view, Bundle bundle)
中的bundle始终为null,因为之前未调用onSaveInstanceState(Bundle outState)
。因此,当我们返回时,bundle为null并再次创建演示者(和视图状态)。在这种情况下,我们如何重用presenter和view状态(而不是重新创建它)?
您可以在下面看到一个虚拟示例。有一个带2个按钮的片段。一个按钮打开一个新片段,另一个按钮转到上一个按钮。当您返回时,将重新创建演示者和视图状态。这不是我需要的,但我在上面描述了为什么它会根据库中的代码而发生。 有没有办法确保我们回去时重用演示者和查看状态?
public class FirstFragment extends MvpViewStateFragment<FirstFragmentView, FirstFragmentPresenter, FirstFragmentViewState> {
public static final String TAG = "TAG";
private Button moveToAnotherFragmentButton;
private Button moveBackButton;
@Nullable
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) {
final View rootFragmentView = inflater.inflate(R.layout.first_fragment, container, false);
moveToAnotherFragmentButton = (Button) rootFragmentView.findViewById(R.id.first_fragment_go_to_another_fragment_button);
moveBackButton = (Button) rootFragmentView.findViewById(R.id.first_fragment_back_button);
return rootFragmentView;
}
@Override
public void onViewCreated(@NonNull final View view, @Nullable final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
moveToAnotherFragmentButton.setOnClickListener(ignored -> addToStack(FirstFragment.class));
moveBackButton.setOnClickListener(ignored -> getFragmentManager().popBackStack());
}
@Override
@NonNull
public FirstFragmentPresenter createPresenter() {
Log.e(TAG, "createPresenter");
return new FirstFragmentPresenter();
}
@NonNull
@Override
public FirstFragmentViewState createViewState() {
Log.e(TAG, "createViewState");
return new FirstFragmentViewState();
}
@Override
public void onNewViewStateInstance() {
Log.e(TAG, "onNewViewStateInstance");
}
private void addToStack(@NonNull final Class<? extends Fragment> fragmentClass) {
final FragmentManager fragmentManager = getFragmentManager();
if (fragmentManager.isDestroyed()) {
throw new UnexpectedException("FragmentManager is destroyed");
}
final Fragment fragment = Fragment.instantiate(getContext(), fragmentClass.getName());
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.replace(R.id.activity_main_content_container, fragment, null)
.addToBackStack(null)
.commit();
}
}