How to open link externally from android webview

You can open link of the WebView externally from android webview without leaving the app. For this action you need to set a WebViewClient class in your WebView. No need to create any custom WebView for that. Let's see the example:

In webview client override shouldOverrideUrlLoading() method just like that, 

@Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Intent i = new Intent(Intent.ACTION_VIEW, request.getUrl());
            startActivity(i);
            return true;
        }

 

Within the shouldOverrideUrlLoading() method simply get the URL from the request and pass into the Intent. See the full example.

 

MainActivity:

package com.legendblogs.android;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    String TAG = "MainActivity";
    Context context;
    WebView mWebView;

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

        mWebView = (WebView) findViewById(R.id.webview);
        mWebview.setWebViewClient(new MyWebViewClient());

        String ENROLLMENT_URL = "file:///android_asset/about_page.html";
        mWebView.loadUrl(ENROLLMENT_URL);

    }

    public final class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Intent i = new Intent(Intent.ACTION_VIEW, request.getUrl());
            startActivity(i);
            return true;
        }

    }
}

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.legendblogs.android.MainActivity">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webview"/>


</RelativeLayout>

 

References stackoverflow:

https://stackoverflow.com/questions/17994750/open-external-links-in-the-browser-with-android-webview

Did you find this page helpful? X