我一直试图在一周的最佳时间做这件事但仍然没有运气。
我有一个带标签的操作栏(操作栏sherlock),我可以切换标签并更改片段。
每个片段都有一个webview,我试图保存webview的状态,以便网页停留在用户离开它的同一页面上。
这是我的片段代码:
public class FragmentB extends SherlockFragment {
WebView myWebView;
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
myWebView.saveState(outState);
Log.w("///////", "onSaveInstanceState");
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
myWebView.restoreState(savedInstanceState);
Log.w("///////", "onActivityCreated");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.w("///////", "onCreate");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mainView = (View) inflater.inflate(R.layout.frag_b, container, false);
myWebView = (WebView) mainView.findViewById(R.id.webview);
Log.w("///////", "onCreateView");
if (savedInstanceState != null){
myWebView.restoreState(savedInstanceState);
Log.w("///////", "restore!");
}
else{
Log.w("///////", "ELSE!");
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.getSettings().setPluginsEnabled(true);
myWebView.getSettings().setBuiltInZoomControls(false);
myWebView.getSettings().setSupportZoom(false);
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.getSettings().setAllowFileAccess(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.loadUrl("http://www.google.com");
}
//return inflater.inflate(R.layout.frag_b, container, false);
return mainView;
}
public class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".mp4"))
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "video/*");
view.getContext().startActivity(intent);
return true;
}
else {
return super.shouldOverrideUrlLoading(view, url);
}
}
}
}
任何帮助都会很棒!
答案 0 :(得分:3)
只有当父活动需要保存其状态时,才会调用片段的onSaveInstanceState
方法;例如,在方向更改期间销毁/重新创建父活动时。因此,当您只是替换片段或在它们之间切换为标签时,将不会调用此方法。
作为特定情况的解决方法,您可以使用onPause
方法将网页视图的状态保存在一个包中,并使用onActivityCreated
方法将其恢复:
// Instance fields
private WebView webView;
private Bundle webViewBundle;
/**
* Save the state of the webview
*/
@Override
public void onPause()
{
super.onPause();
webViewBundle = new Bundle();
webView.saveState(webViewBundle);
}
/**
* Restore the state of the webview
*/
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
if (webViewBundle != null)
{
webView.restoreState(webViewBundle);
}
}
请点击此处了解更多信息:
How to save the state of a WebView inside a Fragment of an Action Bar