0

My Fragment inside a FragmentPagerAdapter contains several WebViews stored in a HashMap. I'm trying to stop them reloading when I rotate the device. I've tried several things but none of them work. This is what I'm currently trying but still no joy.

My webViews HashMap is also being wiped on rotate. Will making it static fix that?

Latest attempt.. After rotation webViewBundle appears to be null.

Relevant Code:

public class SfnViewerFragment extends Fragment {
    private WebView webView;
    private View rootView;
    private HashMap<Long, WebView> webViews = new HashMap<Long, WebView>();
    private static Bundle webViewBundle;

    @Override
    public void onPause() {
        super.onPause();

        webViewBundle = new Bundle();

        if (webView != null) {
            webView.saveState(webViewBundle);
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (webViewBundle != null) {
            webView.restoreState(webViewBundle);
        }
    }

I also had this in my manifest but it still didn't help:

android:configChanges="orientation"
Chris Byatt
  • 3,689
  • 3
  • 34
  • 61

2 Answers2

2

If your API is 13 or higher for android manifest edit code same as below:

android:configChanges="screenSize|orientation"

for more info please take a look at this also.

V.Sis
  • 41
  • 8
1

Try the solution in the link below Handling WebView on Rotation

There are couple of ways.

  1. Do a webview.saveState(savedInstanceState) in onSaveInstanceState() and restore in onRestoreInstanceState.
  2. Handle orientation change cleanup manually. On rotation, all the views inside the layout.xml are destroyed and then recreated. In order to avoid destroying Instead of adding the webview as part of the layout.xml, the webview should be added programatically(via addView()). This way the webview can be removed in onConfigurationChanged() and added back again to the new layout at onCreate(). The link has a better description of the same.

PS: As you might already know, Its not advisable to handle screen rotations manually.

Community
  • 1
  • 1
pravin
  • 1,106
  • 1
  • 18
  • 27