如何将后退按钮添加到Android Web App

时间:2012-04-05 18:38:38

标签: android eclipse web-applications webview

我正在尝试整理网络应用,但找不到通过手机软键包含后退按钮的可能方法。我该怎么做呢? 即我想使用手机上的后退按钮返回上一个查看过的网页。

谢谢

乔丹

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

2 个答案:

答案 0 :(得分:4)

我不建议使用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);
}

答案 1 :(得分:0)

覆盖onBackPressed()方法:

@Override
public void onBackPressed() {

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

这将返回到WebView,直到它无法返回,在这种情况下,它将退出Activity