2014-01-13 131 views
0

在我的webview應用程序中,我打開了一個用於在landscape中顯示路線的網站。我還添加了onKeyDown函數()。但是,當一個鏈接被打開和返回鍵被按下的應用程序是關閉了,幫我解決當按下返回鍵時,webview應用程序強制關閉

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); 
    } 
} 

回答

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導致崩潰

+0

+1添加到更加清晰的WebView'=的WebView(的WebView)findViewById(R.id.webview);'改變這一行 –

0

大概onKeyDown

做到這一點的onBackPressed()方法被調用之前調用。刪除您onKeyDown,並把此一:

@Override 
    public void onBackPressed() { 
     if (webview.canGoBack()) { 
         webview.goBack(); 
         return; 
        } 
     super.onBackPressed(); 
    } 
0

你已經兩次宣佈WebView

試試這個:

替換此通過WebView webview = (WebView) findViewById(R.id.webview);

webview = (WebView) findViewById(R.id.webview); 

,也做到這一點

@Override 
    public void onBackPressed() { 
     webview.goBack(); 

    } 

之前,您將添加onBackPressed()方法請評論中,onKeyDown方法