2013-06-26 136 views
0

我的Android應用程序中的後退按鈕出現問題。我試圖讓它回到前面的頁面,如果無法退出。我挑選開發者網站上的代碼,沒有任何工作。我將不勝感激任何幫助。 以下是我的活動頁面:使用Webview的Android後退按鈕

WebView webView;

@SuppressLint("SetJavaScriptEnabled") 
@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    webView = (WebView)findViewById(R.id.webView); 
    WebSettings webSettings = webView.getSettings(); 
    webSettings.setJavaScriptEnabled(true); 
    webView.setWebViewClient(new myWebView()); 
    webView.loadUrl("http://google.com"); 
    webView.setInitialScale(1); 
    webView.getSettings().setBuiltInZoomControls(true); 
    webView.getSettings().setUseWideViewPort(true); 
} 

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

@Override 
public boolean onCreateOptionsMenu(Menu menu) 
{ 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.diabetes_meal_planner, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) 
{ 
    switch(item.getItemId()) 
    { 
     case R.id.action_settings: 
      //exits app 
      finish(); 
      break; 

     default: 
      break; 
    } 

    return true; 
} 

private class myWebView extends WebViewClient 
{ 
    @Override 
    public boolean shouldOverrideUrlLoading(WebView view, String url) 
    { 
     if(url.startsWith("mailto:")) 
     { 
      String[] email = url.split(":"); 
      Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); 
      emailIntent.setType("plain/text"); 
      emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{email[1]}); 
      emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Send_Us_Your_Email"); 
      Log.v("NOTICE", "Sending Email to" + email[1] + "with subject" + "Send Us Your Feedback"); 
      startActivity(emailIntent); 
     } 

     view.loadUrl(url); 
     return true; 
    } 

} 
+1

儘量確保您充分您的類名:) – frogmanx

+0

去除如果'shouldOverrideUrlLoading'部分,並給試試 – Raghunandan

回答

2

不要這樣做onKeyDown。覆蓋Activity.onBackPressed做到這一點..

+0

你有一些代碼嗎? –

0
@Override 
public boolean onKeyDown(int keyCode, KeyEvent event) { 
    if ((keyCode == KeyEvent.KEYCODE_BACK) && webView!=null && webView.canGoBack()) { 
     webView.goBack(); 
     return true; 
    } 
    return super.onKeyDown(keyCode, event); 
} 

末試試這個,在我的WebView應用程序的工作原理