Android: Retain WebView on Orientation Change Best Practices

CHEN SU
CS Random Thoughts on Tech
2 min readJul 25, 2020

--

Problem Description

  • Many companies embed their common used functionalities in Android and iOS apps’ WebView, e.g. login page
  • On Android, Activity and Fragment’s lifecycles as designed in the Framework go through the process of creating and destroying view very often
  • Users won’t be happy to see their inputs in the html page gets cleared out every time there’s a configuration change, e.g. mostly often orientation change

If WebView is in Activity

Option 1: Lame

  • Add android:screenOrientation=”portrait” to disable portrait/landscape switch

Option 2: Okay

  • Add android:configChanges=”orientation|screenSize” to tell the Framework that you are gonna handle onConfigurationChanged() call back by yourself.
  • Activity’s onCreate/onStart/onResume/onPause/onStop/onDestroy won’t be called when orientation changes, since you tell the Framework it’s your job now
  • No matter where you call webview.loadUrl, it’s only called once, therefore on orientation change, the page won’t get reloaded
  • If the Activity is more complicated, you might still wanna rely on the lifecycle to handle states, instead of handling all things by yourself

Option 3: Okay

  • Allow lifecycle happens in normal way, thus causing WebView to reload page all the time, but make sure you retain and restore states using Bundle
  • This might be cumbersome and cause performance issue

If WebView is in Fragment

One Good Option

  • Set retainInstance to true in the Fragment
  • Even the Activity gets destroyed and re-created, the Fragment attached to that Activity won’t be destroyed and re-created, onCreate is called only once
  • Notice that the Fragment’s view will still be destroyed and re-created
  • It’s best to programmatically keep a WebView instance in memory, instantiate and loadUrl in onCreate, and in onPause remove the WebView from its parent view, since when it hits onCreateView, it’ll return the retained instance again
  • Of course, make sure you know how when to clear the WebView instance when you wire up with Activity and other parts of the app, to avoid memory leak. Either set it to null or remove the WebView from its parent View.
  • Note: Currently I only thought of this clean way to programmatically create WebView and return it in onCreateView, if inflate the UI from xml and still keep the instance, some extra logic needs to be added to onCreateView, depending on how complicated the UI in xml could be

There might be a better way. Let me know your thoughts. Thanks!

--

--