我希望以一种方式实现WebView,它应该在一个Activity中实例化(以及加载html),它不应该在第一页上可见,只有webview在另一个活动中可见。我尝试了以下方法,但无法实现,以下是我的MainActivity
public class MainActivity extends Activity {
private WebView webView = null;
private Button startAppBtn = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createWebView();
startAppBtn = (Button) findViewById(R.id.button1);
startAppBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, SecondActivity.class);
Bundle bundle = new Bundle();
intent.putExtra("state",bundle);
webView.saveState(bundle);
startActivity(intent);
}
});
}
public void createWebView(){
setWebView((WebView) findViewById(R.id.webview1));
getWebView().getSettings().setJavaScriptEnabled(true);
getWebView().getSettings().setDatabaseEnabled(true);
getWebView().getSettings().setLoadWithOverviewMode(true);
getWebView().setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
getWebView().setScrollbarFadingEnabled(false);
getWebView().loadUrl("file:///android_asset/My.html");
getWebView().setVisibility(View.GONE);
}
public WebView getWebView() {
return webView;
}
public void setWebView(WebView webView) {
this.webView = webView;
}
}
以下是SecondActivity,
public class SecondActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
Intent intent = getIntent();
WebView webview = (WebView) findViewById(R.id.webview1);//at this line I am getting exception, I think because webview is in activity_main layout.
webview.restoreState((Bundle) intent.getParcelableExtra("state"));
webview.getSettings().setJavaScriptEnabled(true);
webview.setVisibility(View.VISIBLE);
}
}
我是android世界的新手,在这方面挣扎,请任何人都可以帮我解决这个问题。
答案 0 :(得分:1)
希望这有帮助
第一项活动
startAppBtn = (Button) findViewById(R.id.button1);
startAppBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putString("websiteURL", "file:///android_asset/My.html");
intent.putExtras(bundle);
startActivity(intent);
}
});
第二项活动
String sWebsite;
Bundle bundle = getIntent().getExtras();
if (bundle != null)
{
sWebsite = bundle.getString("websiteURL");
}
else if (bundle== null)
{
System.out.println("Null");
}
WebView webView = (WebView) findViewById(R.id.webview1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(sWebsite);
webView.setWebViewClient(new WebViewClient()
{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
return false;
}
});