24

I have a webview in my android app, but when someone navigates around the site, it opens in a new window, i want it to stay inside the webview.. is there a way to do this easily? Here is the code in my activity:

super.onCreate(savedInstanceState);
    setContentView(R.layout.shop);
    WebView webview;
    webview = (WebView) findViewById(R.id.webview);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.loadUrl("http://www.google.co.uk");
Carla Dessi
  • 9,086
  • 9
  • 39
  • 53
  • possible duplicate of [Link should be open in same web view in Android](http://stackoverflow.com/questions/7308904/link-should-be-open-in-same-web-view-in-android) – thkala Nov 24 '12 at 17:47
  • Possible duplicate of [Link should be open in same web view in Android](https://stackoverflow.com/questions/7308904/link-should-be-open-in-same-web-view-in-android) – Teja Bhagavan Kollepara Jun 05 '18 at 10:30
  • [Read this, all most all about Android WebView)](https://androidride.com/android-webview-example-tutorial-kotlin-java-download-source-code/) – Athira Reddy Oct 08 '19 at 09:46

3 Answers3

43

You'll have to create a WebViewClient:

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

And then set it to your WebView like this:

webview.setWebViewClient(new myWebViewClient());
Ahmad
  • 69,608
  • 17
  • 111
  • 137
  • `shouldOverrideUrlLoading` is deprecated on Android N. Check http://stackoverflow.com/questions/36484074/is-shouldoverrideurlloading-really-deprecated-what-can-i-use-instead – GabrielOshiro May 15 '17 at 21:05
33

Or you can just do that, without creating a new class:

myWebView.setWebViewClient(new WebViewClient());

It works for me.

quent
  • 1,936
  • 1
  • 23
  • 28
1
webview.setWebViewClient(new WebViewClient());

If you want to customize then you should override shouldOverrideUrlLoading (WebView view, String url). but it's deprecated in API 24. You can use public boolean shouldOverrideUrlLoading (WebView view,WebResourceRequest request). actually both of them needs to return false.

Android WebView Example

Athira Reddy
  • 1,004
  • 14
  • 18