8

So I'm very new to Java and I'm using webview in my android app to show my responsive site page. I realize I should develop a dedicated app but I'm just not that good yet.

That being said, when someone uses a link in my site, it tries to open a browser window on their phone and I would rather it keep them in the app. Here is my current webview configuration. I've tried a few solutions I've read here but none of them seem to work (likely due to my limited knowledge).

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

        String url ="http://dirtywasted.com/";
        WebView view=(WebView) this.findViewById(R.id.webView);
        view.getSettings().setJavaScriptEnabled(true);
        view.loadUrl(url);
    }

What should I add to this to keep links clicked inside the app?

Jeff Fletcher
  • 81
  • 1
  • 2

1 Answers1

6

You can set a WebClient to webview and override the shouldOverrideUrlLoading like:

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

    String url ="http://dirtywasted.com/";
    WebView view=(WebView) this.findViewById(R.id.webView);
    view.getSettings().setJavaScriptEnabled(true);
    view.setWebViewClient(new WebViewClient() {
            @Override
            public bool shouldOverrideUrlLoading(WebView view, String url) {
                //url will be the url that you click in your webview.
                //you can open it with your own webview or do
                //whatever you want

                //Here is the example that you open it your own webview.
                view.loadUrl(url);
                return true;
            }       
         });
    view.loadUrl(url);
}
buptcoder
  • 2,692
  • 19
  • 22
  • 5
    In fact, you don't need to override `shouldOverrideUrlLoading`, just setting a WebViewClient does the job: `view.setWebViewClient(new WebViewClient())` – Mikhail Naganov Mar 13 '15 at 08:46
  • But if you want to handle the url with other behaviour, for example, open it in other activity, you should override this method to get the url. – buptcoder Mar 14 '15 at 03:44