Android webView saveState

2019-01-14 12:04发布

I have a tabhost with 3 tabs. In each of these tabs there is a webiview. When i click a tab the webview need to "reload" even when i have been there before, it have not been saved. Is there any way to save the webview ?

3条回答
我只想做你的唯一
2楼-- · 2019-01-14 12:33

Alternatively you can look into using fragments with your tabHost. when entering another webView you can set fragment to hide and the other to show. when you return to the previous fragment the content will not have been destroyed. Thats how i did it and it worked for me.

查看更多
再贱就再见
3楼-- · 2019-01-14 12:37

restoreState was never reliable. And come 2015 the documents accept the fact. (The change was probably made to the documents around 2014). This is what it says now.

If it is called after this WebView has had a chance to build state (load pages, create a back/forward list, etc.) there may be undesirable side-effects. Please note that this method no longer restores the display data for this WebView.

And the corresponding entry for saveState() speaks thus:

Please note that this method no longer stores the display data for this WebView.

What you really should do inside the onCreate method is to call webView.loadUrl() if you want to display the last visited url, please see this answer:

If you are concerned about the webview reloading on orientation change etc.

you can set your Activity to handle the orientation and keyboardHidden changes, and then just leave the WebView alone

查看更多
冷血范
4楼-- · 2019-01-14 12:43

This can be handled by overrwriting onSaveInstanceState(Bundle outState) in your activity and calling saveState from the webview:

@Override
protected void onSaveInstanceState(Bundle outState) {
    webView.saveState(outState);
    super.onSaveInstanceState(outState); 
}

Then recover this in your onCreate after the webview has been re-inflated of course:

@Override
public void onCreate(final Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.blah);
   WebView webview = (WebView)findViewById(R.id.webview);
   if (savedInstanceState != null)
      webview.restoreState(savedInstanceState);
   else
      webview.loadUrl(URLData)
}
查看更多
登录 后发表回答