我的应用程序中有一个加载动态内容的 WebView
,我希望 View 在设备旋转时保持不变。所以我写了下面几行代码:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
在我的 onCreate() 中:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
if(D.bug){
Log.i(TAG, "Restoring browser state");
}
mWebView.restoreState(savedInstanceState);
} else {
if(D.bug){
Log.i(TAG, "Not restoring browser state");
}
mWebView.loadUrl("file:///android_asset/html/browser_3col.html");
}
return mWebView;
}
但这有效地重新加载了页面。我想传递动态生成的 HTML。
我想通过一个JavascriptInterface
转储整个文档HTML,将其存储在outState 中,然后通过JavascriptInterface
重新设置它。
这是个好方法吗? WebView
没有方法可以让我获取其内部 HTML 吗?
最佳答案
我目前的解决方案有以下代码:
在我的 JavaScript 代码中:
window.JSInterface.dumpInnerHtml(document.documentElement.innerHTML);
在我的 JavascriptInterface
中:
@JavascriptInterface
public void dumpInnerHtml(String htmlDump) {
if (!mBrowseFragment.isDetached()) {
mBrowseFragment.updateWebviewHtml(htmlDump);
}
}
在 onSaveInstance()
中:
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
outState.putString(INSTANCE_CONTAINER_HTML, mCurrentHtmlDump);
在 onCreate()
中:
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
String restoredHtml = savedInstanceState
.getString(INSTANCE_HTML);
if (restoredHtml != null) {
mWebView.loadData(restoredHtml, "text/html", "utf-8");
}
}
它几乎可以工作。但是我有一些问题。 loadData() 似乎不解释脚本标签。 (我的 js 函数坏了。),我觉得这个问题可以更优雅地解决。
关于android - 恢复包含动态生成的 HTML 的 webview 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14020934/