Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebView: Stop from opening links in browser and keep in app

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?

like image 258
Jeff Fletcher Avatar asked Mar 13 '15 01:03

Jeff Fletcher


1 Answers

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);
}
like image 176
buptcoder Avatar answered Oct 18 '22 14:10

buptcoder