我有一个应用程序,在其中我有一个WebView,我显示一些网站。它是有效的,点击网页中的链接会转到我的应用程序中的网站下一页。但当我点击手机的返回按钮时,它会直接带我进入我的应用程序。我想回到网站的上一页。我该怎么做呢?

下面是我正在使用的代码示例:

public class Webdisplay extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.webdisplay);

        getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
                Window.PROGRESS_VISIBILITY_ON); 

        Toast loadingmess = Toast.makeText(this,
                "Cargando El Diario de Hoy", Toast.LENGTH_SHORT);
        loadingmess.show();

        WebView myWebView;

        myWebView = (WebView) findViewById(R.id.webview);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadUrl("http://www.elsalvador.com");
        myWebView.setWebViewClient(new WebViewClient());
        myWebView.setInitialScale(1);
        myWebView.getSettings().setBuiltInZoomControls(true);
        myWebView.getSettings().setUseWideViewPort(true);

        final Activity MyActivity = this;
        myWebView.setWebChromeClient(new WebChromeClient() 
        {
            public void onProgressChanged(WebView view, int progress)   
            {
                MyActivity.setTitle("Loading...");
                MyActivity.setProgress(progress * 100); 

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

当前回答

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

其他回答

你应该在你的类中使用以下库来处理onBackKeyPressed。 canGoBack()检查webview是否可以引用前一页。如果可能,则使用goBack()函数引用前一页(返回)。

 @Override
        public void onBackPressed() {
          if( mWebview.canGoBack()){
               mWebview.goBack(); 
           }else{
            //Do something else. like trigger pop up. Add rate app or see more app
           }
  }

完整的参考下一个按钮和进度条:放回和下一个按钮在webview

如果你想在点击手机的后退按钮时回到后退页,使用这个:

@Override
public void onBackPressed() {
    if (webView.canGoBack()) {
        webView.goBack();
    } else {
        super.onBackPressed();
    }
} 

你也可以像这样创建自定义后退按钮:

btnback.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if (wv.canGoBack()) {
                wv.goBack();
            }
        }
    }); 

FoamyGuy的第一个答案是正确的,但我有一些补充;低声誉不允许我发表评论。如果由于某些原因您的页面加载失败,请确保您设置了一个标记来记录失败,然后在onBackPressed覆盖上检查它。否则,你的canGoBack()将永远执行而不前往实际的back活动,如果它在那里:

//flag with class wide access 
public boolean ploadFailFlag = false;

//your error handling override
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
    onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
    ploadFailFlag = true;       //note this change 
    .....
    .....
}

//finally to the answer to this question:
@Override
public void onBackPressed() {
    if(checkinWebView.canGoBack()){
        //if page load fails, go back for web view will not go back - no page to go to - yet overriding the super 
        if(ploadFailFlag){
            super.onBackPressed();
        }else {
            checkinWebView.goBack();
        }
    }else {
        Toast.makeText(getBaseContext(), "super:", Toast.LENGTH_LONG).show();
        super.onBackPressed();
    }
}

在onBackPressed中也应该检查聚焦

    @Override
    public void onBackPressed() {
        if (mWebview.isFocused() && mWebview.canGoBack()) {
            mWebview.goBack();       
        } else {
            super.onBackPressed();
            finish();
        }
    }

如果有人想在片段中处理webView的backPressed,那么他可以使用下面的代码。

Copy below code into your Activity class (that contains a fragment YourFragmmentName) @Override public void onBackPressed() { List<Fragment> fragmentList = getSupportFragmentManager().getFragments(); boolean handled = false; for(Object f: fragmentList) { if(f instanceof YourFragmentName) { handled = ((YourFragmentName)f).onBackPressed(); if(handled) { break; } } } if(!handled) { super.onBackPressed(); } } Copy this code in the fragment YourFragmentName public boolean onBackPressed() { if (webView.canGoBack()) { webView.goBack(); return true; } else { return false; } }

笔记

Activity应该替换为您正在使用的实际Activity类。 YourFragmentName应该替换为Fragment的名称。 在YourFragmentName中声明webView,以便可以从函数中访问它。