I have a webview, I need to save the state of that webview when changing the orientation. I want to load the different layout when changing the orientation, but am using fragment. How to solve this problem ?
Implement this on your fagment that contains the WebView:
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);
}
And add this in your Manifest <activity>
tag:
<activity
...
android:configChanges="orientation|screenSize"
... ></activity>
private 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.