当我们这样做popBackStack
并返回到后栈中的前一个片段时,onViewCreated(View view, Bundle bundle)
由于onSaveInstanceState(Bundle outState)
之前没有调用过,方法中的包始终为空。因此,当我们返回时,bundle 为空,并且再次创建了演示者(和视图状态)。在这种情况下,我们如何重用演示者和视图状态(而不是重新创建它)?
您可以在下面看到一个虚拟示例。有一个带有 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();
}
}