![](/img/trans.png)
[英]Android Webview app force closes while pressing the back navigation key
[英]webview app force closes when back key is pressed
在我的webview應用程序中,我打開了一個網站來顯示風景,同時還添加了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);
}
}
更改
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
導致崩潰
可能在調用onKeyDown
之前先調用onBackPressed()方法
做這個。 刪除您的onKeyDown
並將其放在這里:
@Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
return;
}
super.onBackPressed();
}
您已經兩次聲明了WebView
嘗試這個:
替換此WebView webview = (WebView) findViewById(R.id.webview);
通過
webview = (WebView) findViewById(R.id.webview);
並做到這一點
@Override
public void onBackPressed() {
webview.goBack();
}
在添加onBackPressed()方法之前,請先注釋onKeyDown方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.