Skip to content Skip to sidebar Skip to footer

WebView Prevent Reloading In RetainInstance Fragment

I am having a problem preventing a WebView from reloading when inside a fragment with retainInstance set to true. The routes I have tried: SaveInstanceState (Doesn't pass a bundle

Solution 1:

You can do this pretty easily. Since you're already retaining the instance, keep a reference to the WebView in the Fragment and detach it from the parent when the Fragment's onDestroyView() is called. If it's non-null, just return that in onCreateView(). For example:

public class RetainedWebviewFragment extends Fragment {
    private WebView mWebView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mWebView == null) {
            mWebView = new WebView(getActivity());
        }

        return mWebView;
    }

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

        if (getRetainInstance() && mWebView.getParent() instanceof ViewGroup) {
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
        }
    }
}

However, you will leak one reference to the first Activity on the first orientation change -- something I've not yet figured out how to avoid. tThere's no way to set the context on a View to my knowledge. This does work, though, if you're okay with that one memory leak.

EDIT: Alternatively, if you're instantiating it programmatically as I'm doing in this example, you could just use getActivity().getApplicationContext() to avoid leaking the activity. If you use the provided LayoutInflater, it will give the application's context to the Views when inflating.

Don't use the application context for a WebView -- this will cause unexpected crashes when showing dropdown views and potentially other problems.


Post a Comment for "WebView Prevent Reloading In RetainInstance Fragment"