我的活动A带有功能性WebView1和3个按钮。我正在onPause下保存Webview1状态,所以一旦活动B打开,WebView1的状态就已经保存了。我的问题是每当我打开Activity B并尝试将WebView1保存状态加载到活动B上的WebView11时它会给我一个空指针(手机上的白色屏幕)。如何保存活动A的webview状态,以便可以在活动B中恢复?
示例:我正在活动页面底部的webview我要保存该状态所以一旦我打开活动2 webview它会将我带到同一页面的底部而不是重新加载页面。
主要活动
public class MainActivity extends Activity {
public Bundle webViewBundle;
WebView wv;
Button bt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView) findViewById(R.id.webView1);
WebSettings webSettings = wv.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
wv.loadUrl("http://www.google.com");
wv.setWebViewClient(new myWebViewClient());
addListenerOnbt1();
}
public void addListenerOnbt1() {
// Select a specific button to bundle it with the action you want
bt1 = (Button) findViewById(R.id.button1);
bt1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Activity2.class);
Bundle name=webViewBundle;
intent.putExtra("name", name);
startActivity(intent);
finish();
}
});
}
@Override
public void onPause()
{
super.onPause();
webViewBundle = new Bundle();
wv.saveState(webViewBundle);
}
>
活性2
public class Activity2 extends Activity {
WebView wv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_main);
Bundle b = new Bundle();
b = getIntent().getExtras();
String name = b.getString("name");
final RelativeLayout rl = new RelativeLayout(this);
wv2 = (WebView) findViewById(R.id.webView11);
WebSettings webSettings = wv2.getSettings();
webSettings.setJavaScriptEnabled(true);
wv2.restoreState(b); // This line returns Null or white screen
}
} >
提前感谢您的帮助。
答案 0 :(得分:3)
尝试保存WebView状态并一次启动下一个活动。
Bundle state = new Bundle();
webView.saveState(state);
Intent intent = new Intent(MainActivity.this, Activity2.class);
intent.putExtra("state", state);
intent.putExtra("name", name);
然后从额外恢复它。
webView.restoreState((Bundle)intent.getParcelableExtra("state"));