2012-04-05 18 views
-1

我正在嘗試整理一個網絡應用程序,但找不到通過手機軟鍵包含使用後退按鈕的可能方式。我怎麼能這樣做呢? 即我想使用手機上的後退按鈕返回到先前瀏覽過的網頁。如何將後退按鈕添加到Android Web App

謝謝

喬丹

package com.wear2gym; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.Window; 
import android.webkit.WebChromeClient; 
import android.webkit.WebView; 
import android.webkit.WebViewClient; 
import android.widget.Toast; 

public class Wear2gym extends Activity 
{ 
    final Activity activity = this; 



    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     this.getWindow().requestFeature(Window.FEATURE_PROGRESS); 
     setContentView(R.layout.main); 
     WebView webView = (WebView) findViewById(R.id.WebView); 
     webView.getSettings().setJavaScriptEnabled(true); 

     webView.setWebChromeClient(new WebChromeClient() { 
      public void onProgressChanged(WebView view, int progress) 
      { 
       activity.setTitle("Pumping some iron..."); 
       activity.setProgress(progress * 100); 

       if(progress == 100) 
        activity.setTitle(R.string.app_name); 
      } 
     }); 

     webView.setWebViewClient(new WebViewClient() { 
      @Override 
      public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) 
      { 
       Toast.makeText(activity, "Sorry but there is no internet connection! " , Toast.LENGTH_LONG).show(); 
       view.loadUrl("file:///android_asset/nointernet.html"); 
       // Handle the error 
      } 

      @Override 
      public boolean shouldOverrideUrlLoading(WebView view, String url) 
      { 
       view.loadUrl(url); 
       return true; 
      } 
     }); 

     webView.loadUrl("http://wear2gym.co.uk"); 
     webView.canGoBack(); 
    } 
} 

回答

0

覆蓋的onBackPressed()方法:

@Override 
public void onBackPressed() { 

    if(mWebView.canGoBack()) { 
     mWebView.goBack(); 
    } 
    else { 
     super.onBackPressed(); 
    } 
} 

這會回到上WebView,直到它不能回去,在這種情況下,它會退出Activity

+1

@ Profete162正確的,但大多數應用程序有一個目標大於5(只有1%的有源器件小於API等級5) – 2012-04-05 18:53:51

+0

爲數百萬設備的1%更改一行代碼似乎很有趣;-) – 2012-04-22 12:54:50

3

我不推薦onBackPressed()爲那唯一可用的,因爲API級別5

你會發現偉大的信息在這裏:http://developer.android.com/guide/webapps/webview.html

@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) && myWebView.canGoBack() { 
     myWebView.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

您好!感謝您的回覆。 哪裏會是最好的地方添加這個? 對不起,我是Android開發領域的新手! – 2012-04-05 19:02:18

+0

就在最後一個括號}之前。此外,請不要忘記投票和/或接受答案,這是該網站的工作原理。 – 2012-04-05 19:55:23

相關問題