0

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

谢谢

约旦

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

2 回答 2

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);
}
于 2012-04-05T18:49:27.617 回答
0

覆盖onBackPressed()方法:

@Override
public void onBackPressed() {

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

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

于 2012-04-05T18:47:28.803 回答