在我的webview应用程序中,我打开了一个网站,用于在横向中显示lways。我还添加了onKeyDown函数()。但是当打开链接并按下后退键时,应用程序将关闭。请帮助我解决
WebActivity.java
package com.example.samworkshops;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebActivity extends Activity {
public WebView webview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new WebViewClient());
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.loadUrl("http://app.samworkshops.org");
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
}
答案 0 :(得分:1)
更改
WebView webview = (WebView) findViewById(R.id.webview);
// declared again and initialized. becomes local to onCreate
到
webview = (WebView) findViewById(R.id.webview);
因为你已经拥有
public class WebActivity extends Activity {
public WebView webview; // declared but this is never initialized
我猜它是导致崩溃的NullPointerException
答案 1 :(得分:0)
可能在调用onKeyDown
这样做。删除onKeyDown
并将其放入:
@Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
return;
}
super.onBackPressed();
}
答案 2 :(得分:0)
您有两次声明WebView
试试这个:
替换此WebView webview = (WebView) findViewById(R.id.webview);
由
webview = (WebView) findViewById(R.id.webview);
并且也这样做
@Override
public void onBackPressed() {
webview.goBack();
}
在你添加onBackPressed()方法之前请注释onKeyDown方法