Search code examples
androidandroid-savedstateconductor

Nested RouterPagerAdapter's not restoring state on rotation


The root controller, which has a RouterPagerAdapter, hosts controller A which has its own RouterPagerAdapter.

Controller A1 is hosted by controller A

[ Root Controller ]
[   A   ] [   B   ]
[A1] [A2]

Upon rotation, Root Controller, A and A1 receive their onSaveInstanceState/onSaveViewState, but neither A nor A1 is receives it onRestoreInstanceState/onRestoreViewState.

Why is this so? What is the correct implementation to ensure that all children will have their state restored?


Solution

  • onSaveViewState will be called, but onRestoreViewState will not be called due to the viewPager.setAdapter(null); line.

    The example in Conductor's docs sets the adapter to null when the view is being destroyed.

    Override protected void onDestroyView(@NonNull View view) {
        viewPager.setAdapter(null);
        super.onDestroyView(view);
      }
    

    Because of this, RouterPagerAdapter will call configureRouter to which the router does not have a root controller, and will new Cont()

    if (!router.hasRootController()) {
          router.setRoot(RouterTransaction.with(new Cont()));
        }
    

    Also note, when nesting a viewPager within another, both should have unique ids, else on rotation will overwrite the save state of the parent viewPager, and will show the wrong current item.