Search code examples
androidwebviewhistoryscreen-orientationback-stack

webview backstack lost after screen rotation, back button history of pages, Android


I have a WebView in an Activity and it works great in one screen orientation. I can navigate around to different pages on a website and when I hit the back button it goes back to the the previous pages that I visited before,

however when I rotate the Android tablet from one orientation to another. like from portrait to landscape, this history is lost. I passed the the URL that the WebView was currently on to the next orientation by savedInstanceState.

After the screen rotation the newly created WeView opens the page to the URL as expected. when I hit the back button it does not go anywhere.

How do I fix this problem?

here is some of my code, it is the part where I handle the back button.

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {   

if (keyCode == KeyEvent.KEYCODE_BACK){

    if (pageView.canGoBack()){

        if((coverImage.getVisibility())==(View.VISIBLE)){
            setYouTubeScreenDecor(false);

          FragmentManager fragmentManager = getFragmentManager();
          FragmentTransaction fragmentTransaction = 
             fragmentManager.beginTransaction();
          fragmentTransaction.hide(youTubePlayerFragment);
          fragmentTransaction.commit();
          if(playerVision!=null){
              playerVision.pause();
          }

         return true;

    } // end if
        else {
            pageView.goBack();

         return false;

        } // end else

    } // end if pageview.canGoBack

   } // event keycode

    return true;

 } // end if keyCode == KeyEvent.KEYCODE_BACK

Solution

  • I found the answer. a case of RTFM.

    WebBackForwardList restoreState(Bundle inState) Restores the state of this WebView from the given Bundle.

    WebBackForwardList saveState(Bundle outState) Saves the state of this WebView used in onSaveInstanceState(Bundle).