的WebView prevent在RetainInstance片段重装 [英] WebView prevent reloading in RetainInstance fragment

查看:250
本文介绍了的WebView prevent在RetainInstance片段重装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,$ P $重装从里面时用retainInstance片段设置为true pventing一个web视图。

I am having a problem preventing a WebView from reloading when inside a fragment with retainInstance set to true.

我已经试过的路线:

SaveInstanceState(不传递,因为retainInstance旋转的束)
这是保存在和的onSaveInstanceState恢复了创建自定义捆绑
保持的WebView参考,并试图将其添加回视图层次

SaveInstanceState (Doesn't pass a bundle on rotation because of retainInstance) A custom bundle which is saved on onSaveInstanceState and restored in create Keeping the WebView reference and attempt to add it back to the view hierarchy

必须有一个更简单的方法?

There must be an easier way?

推荐答案

您可以轻松地做到这一点pretty。既然你已经保留的实例,存到的WebView 在片段的引用,并从父取下它,当片段的onDestroyView()被调用。如果它不为null,只返回在onCreateView()。例如:

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);
        }
    }
}

不过,你会泄漏一个引用的第一个方向变化的第一个活动 - 这是我一直没有想出如何避免。 tThere没有办法设置在查看我的知识范围内。这并不工作,不过,如果你没事与一个内存泄漏。

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.

编辑:另外,如果你是编程实例化它,因为我在这个例子中我做,你可以只使用 getActivity()getApplicationContext()以避免泄漏的活性。如果您使用提供LayoutInflater,它会给应用程序上下文视图充气时。

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.

不要使用一个的WebView应用程序上下文 - 显示下拉列表视图和其它潜在的问题时,这将导致意外崩溃

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

这篇关于的WebView prevent在RetainInstance片段重装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆