Proper Rotation with WebView

Try rotating your screen. While it does work correctly, you will notice that the WebView has to completely reload the web page. This is because WebView has too much data to save it all inside onSaveInstanceState(…). It has to start from scratch each time it is re-created on rotation.

You may think the easiest way to resolve this problem would be to retain PhotoPageFragment. However, this would not work, because WebView is part of the view hierarchy and is thus still destroyed and re-created on rotation.

For some classes like this (VideoView is another one), the Android documentation recommends that you allow the activity to handle the configuration change itself. This means that instead of the activity being destroyed on rotation, it simply moves its views around to fit the new screen size. As a result, WebView does not have to reload all of its data.

To tell PhotoPageActivity to handle its own darned configuration changes, make the following tweak to AndroidManifest.xml.

Listing 30.11  Handling configuration changes yourself (AndroidManifest.xml)

<manifest ... >
    ...
    <activity
          android:name=".PhotoPageActivity"
          android:configChanges="keyboardHidden|orientation|screenSize" />
      ...
</manifest>

This attribute says that if the configuration changes because the keyboard was opened or closed, due to an orientation change, or due to the screen size changing (which also happens when switching between portrait and landscape after Android 3.2), then the activity should handle the change itself.

And that is it. Try rotating again and admire how smoothly the change is handled.

Dangers of handling configuration changes

That is so easy and works so well that you are probably wondering why you do not do this all the time. It seems like it would make life so much easier. However, handling configuration changes on your own is a dangerous habit.

First, resource qualifier-based configuration changes no longer work automatically. You instead have to manually reload your view when a configuration change is detected. This can be more complicated than it sounds.

Second, and more important, allowing the activity to handle configuration changes will likely cause you to not bother with overriding Activity.onSavedInstanceState(…) to stash transient UI states. Doing so is still necessary, even if the activity is handling configuration changes on its own, because you still have to worry about death and re-creation in low-memory situations. (Remember, the activity can be destroyed and stashed by the system at any time if it is not in the running state, as shown in Figure 3.14 .)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.177.223