更改方向时如何在片段中保存WebView状态?

时间:2014-04-17 09:24:32

标签: android android-fragments android-webview

我有一个webview,我需要在更改方向时保存该webview的状态。我想在更改方向时加载不同的布局,但我正在使用片段。如何解决这个问题?

2 个答案:

答案 0 :(得分:6)

在包含WebView:

的fagment上实现此功能
private Bundle webViewBundle;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    setRetainInstance(true);
    ...
}

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.my_layout, container, false);
    wv = (WebView) v.findViewById(R.id.webView);

    if (webViewBundle != null)
    {
        wv.restoreState(webViewBundle);
    }
    else
    {
        wv.loadUrl("http://www.mysite.mydomain");
    }

    return v;
}

public void onPause() {
    super.onPause();
    webViewBundle = new Bundle();
    wv.saveState(webViewBundle);
}

并在您的Manifest <activity>标记中添加此内容:

 <activity
        ...
        android:configChanges="orientation|screenSize"
        ... ></activity>

答案 1 :(得分:0)

私人WebView wv;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}


public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.webview_layout, container, false);
    wv = v.findViewById(R.id.web_view);

    WebSettings webSettings = wv.getSettings();
    webSettings.setJavaScriptEnabled(true);

    wv.setWebViewClient(new WebViewClient());
    wv.loadUrl("http://example.com/");

    return v;
}