我有一个显示 WebView 的片段,为了保留正在显示的网站,我保存状态如下:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
/*Saves the currently displayed webpage and the browser history*/
webView.saveState(outState);
}
然后我像这样恢复它:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_page_detail,
container, false);
webView = (WebView) rootView.findViewById(R.id.page_detail_webview);
progressBar = (ProgressBar) rootView.findViewById(R.id.op_progress);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(progress);
if (progress == 100) {
progressBar.setVisibility(View.GONE);
}
}
});
webView.setWebViewClient(new StockStreamWebViewClient());
webView.getSettings().setBuiltInZoomControls(true);
/*Restores the saved browser history if there is any*/
if (savedInstanceState != null) {
webView.restoreState(savedInstanceState);
} else if (mItem != null) {
webView.loadUrl(mItem.content);
}
return rootView;
}
为了让用户返回 WebView,我的 Activity 中有以下代码:
@Override
public void onBackPressed() {
if (!clientFragment.onBackPressed()) {
super.onBackPressed();
}
}
}
我的片段中的这段代码:
public boolean onBackPressed() {
if (webView != null && webView.canGoBack()) {
webView.goBack();
return true;
} else {
return false;
}
}
当我旋转我的设备时,屏幕正确绘制并且 WebView 恢复它的上一页,但是当我按下时,WebView 为空。
为什么会这样?
谢谢, 安赫