当我使用OTG(A4TECH GX-110)连接外部键盘时,我的Activity正在从头开始创建。这导致重新创建WebView
。
这是我的XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="uz.cp.oxmini.MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/wvOx" />
</RelativeLayout>
我尝试保存WebView
状态,然后保存onCreate()
方法以恢复已保存的状态。
private WebView mWebview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebview = new WebView(this);
if (savedInstanceState != null){
mWebview.restoreState(savedInstanceState);
}
else {
mWebview.loadUrl("http://joerichard.net");
setContentView(mWebview);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
mWebview.saveState(outState);
}
但结果是带灰色背景的屏幕
有什么问题?怎么解决?
答案 0 :(得分:0)
我添加了onRestoreInstanceState并修改了onSaveInstance方法。现在我在onRestoreInstanceState中恢复webview状态。此外,我已更改检查savedInstanceState是否为null:
private WebView mWebview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebview = new WebView(this);
if (savedInstanceState == null) {
mWebview.loadUrl("http://joerichard.net");
}
setContentView(mWebview);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebview.saveState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mWebview.restoreState(savedInstanceState);
}