Search code examples
androidandroid-webview

When the back button is pressed in webview the app exit


Instead of going back to the previous page, the app is closed when pressed the back button...

the back button code is not working for this condition. i tried every possible code but it still not woring

<?xml version="1.0" encoding="utf-8"?>

<WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    </WebView>

main_activity:

 public class MainActivity extends AppCompatActivity {

        WebView mywebView;


        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mywebView = (WebView) findViewById(R.id.webview);
        mywebView.getSettings().setJavaScriptEnabled(true);
        mywebView.loadUrl("http://www.google.co.in");

            mywebView.setWebViewClient(new WebViewClient(){

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


   }
   //goto previous page

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

Solution

  • I had many hours wasted on this one lately. Please look closely. WebView Docs shouldoverrideUrlLoading

    If a WebViewClient is provided, returning true causes the current WebView to abort loading the URL, while returning false causes the WebView to continue loading the URL as usual.

    So the shouldOverrideUrlLoading return should be false, note true. True will force both disable the onbackpress override method ( i think) and loading further Urls.

    So the code should be like:

    @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url){//condition or the code
                    view.loadUrl(url);
                    return false;
                }
            });
    

    also I used :

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

    hope I this will help in future!