I am learning how to implement a "single activity - multiple fragments" architecture. It is widespread approach nowadays as I understand and you can find a lot of articles on this topic. For example this one http://vinsol.com/blog/2014/09/15/advocating-fragment-oriented-applications-in-android/.
There are two types of fragments in such architecture - parent and child from my point of view.
Parent fragment is started from the top level, from a drawer for example. I prefer to do it in the following manner:
public void startParent(Fragment fragment) {
manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(fragment.getClass().getCanonicalName());
transaction.commit();
}
Also, there is child fragment that is started like this:
public void startChild(Fragment fragment) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(fragment.getClass().getCanonicalName());
transaction.commit();
}
In both cases, the manager
is standard fragment manager provided by activity.
There is only one difference between the provided methods. In the first case back stack is cleared to start new fragment from scratch. On the seconds one, it just pushed to the back stack.
As a result back stack may look like: Parent -> Child1 -> Child2
A user navigates between fragments or just start the new sequence from the top level (drawer).
When a user presses back button the last fragment is popped back from the stack. As I understand you even don't need to override onBackPressed()
method of activity.
It works fine until screen configuration is changed. When screen configuration is changed onBackPressed()
leads to well-known error java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
There are a lot of questions have been asked already about this issue on StackOverflow but I didn't find the right answer for my case. People suggest to call commitAllowingStateLoss()
and so on but it is unrelated to my case. I do not want to start new fragment I just want to go back to previous one.
So my question is following: is my understanding correct that there is no way to navigate back through back stack after screen configuration change? All you have to do is invalidate it and start from scratch?