Create a Web Browser

How to create a Web Browser, Step-by-Step

1. Create a new android project called MyWebView. Leave the activity name as MainActivity.java. Leave the layout name as main.xml.

2. Add a WebView to the res/layout/main.xml file.

3. Now let's add a EditText box at the top so you can type in the URL you would like to navigate to. Add this code right before your WebView.


4. Now let's set the default text for the EditText to be the google web site. Text should be : https://www.google.com/




5. This, however, is not linked to the URL yet. It is just displaying https://www.google.com/
To be able to navigate to a different URL by typing it into EditText we need get the contents of the EditText.

6. Change the loadUrl to the contents of the EditText, instead of "https://www.google.com/"

        webView.loadUrl(editText.getText().toString());

7. Right now if you search for "birds" using the default Google page, a web listing will display in your WebView. However, if you click on one of the search listing links, the link will open in your default browser, or display a list of browsers in which to open the link. 

To remedy this, we need to add the below import to the MainActivity.java file.

import android.webkit.WebViewClient;
import android.content.Intent;
import android.net.Uri;


Then add the below code to the onCreate Method in MainActivity

webView.setWebViewClient(new WebViewClient(){ 
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
       if (url != null && url.startsWith("http://")) {
           view.getContext().startActivity( new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
           return true;
       } else { 
            return false; 
       } 
    } 
});