我有一个应用程序,在其中我有一个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);
            }
        });
    }
}

我使用类似这样的东西在我的活动与WebViews:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
                return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}

编辑:

为了让这段代码工作,你需要添加一个包含WebView的Activity字段:

private WebView mWebView;

在onCreate()方法中初始化它,您应该可以开始了。

mWebView = (WebView) findViewById(R.id.webView);

为什么不使用onBackPressed()?

@Override
public void onBackPressed() {
    // super.onBackPressed(); Do not call me!

    // Go to the previous web page.
}

如果使用Android 2.2及以上版本(这是现在大多数设备),下面的代码将得到你想要的。

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

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

这就是我的解。它也适用于Fragment。

webView.setOnKeyListener(new OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            WebView webView = (WebView) v;
            
            switch(keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (webView.canGoBack()) {
                        webView.goBack();
                        return true;
                    }
                    break;
            }
        }
        
        return false;
    }
});

这是一个确认退出的代码:

@Override
    public void onBackPressed()
    {
        if(webView.canGoBack()){
            webView.goBack();
        }else{
            new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Exit!")
            .setMessage("Are you sure you want to close?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();    
                }

            })
            .setNegativeButton("No", null)
            .show();    
        }   
    }

在onBackPressed中也应该检查聚焦

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

你应该在你的类中使用以下库来处理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();
    }
}

下面是Kotlin的解决方案:

override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
    if (event?.action != ACTION_UP || event.keyCode != KEYCODE_BACK) {
        return super.onKeyUp(keyCode, event)
    }

    if (mWebView.canGoBack()) {
        mWebView.goBack()
    } else {
        finish()
    }
    return true
}

官方Kotlin方式:

override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
    // 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)
}

https://developer.android.com/guide/webapps/webview.html#NavigatingHistory


使用此代码回到页面,当最后一页来了,然后退出活动

 @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent=new Intent(LiveImage.this,DashBoard.class);
        startActivity(intent);
    }

如果有人想在片段中处理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,以便可以从函数中访问它。


在芬兰湾的科特林:

override fun onBackPressed() {
    when {
        webView.canGoBack() -> webView.goBack()
        else -> super.onBackPressed()
    }
}

webView -如果使用合成引用,webView组件在xml中的id。


你可以尝试在一个片段webview:

private lateinit var webView: WebView

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val root = inflater.inflate(R.layout.fragment_name, container, false)
    webView = root!!.findViewById(R.id.home_web_view)
    var url: String = "http://yoururl.com"
    webView.settings.javaScriptEnabled = true
    webView.webViewClient = WebViewClient()
    webView.loadUrl(url)
    webView.canGoBack()
    webView.setOnKeyListener{ v, keyCode, event ->
        if(keyCode == KeyEvent.KEYCODE_BACK && event.action == MotionEvent.ACTION_UP
            && webView.canGoBack()){
            webView.goBack()
            return@setOnKeyListener true
        }
        false
    }
    return root
}

 WebView mWebView;

 mWebView = findViewById(R.id.webView);

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

我想我有点晚了,但根据android文档,你可以有自定义反向导航在碎片内完成以下一段代码。

 requireActivity().onBackPressedDispatcher.addCallback(this) {
            // Handle the back button event
            if (binding.webView.canGoBack()){
                binding.webView.goBack()
            } else {
                findNavController().popBackStack()
            }
        }

你可以自定义什么做,当你的webView不能返回根据你的需要。